开发者

Yii framework: HAS_MANY through on condition not working?

开发者 https://www.devze.com 2023-03-11 03:48 出处:网络
I don\'t know what\'s happening because thing does not add up so going to ask the community for help.

I don't know what's happening because thing does not add up so going to ask the community for help.

I have a mortgage which has 1 primary applicant and 1 or more (many) co-applicants.

The relation in my mortgage model is:

// primary applicant connection
'primaryApplicantConnection' => array(self::HAS_ONE, 'PersonToMortgage', 'mortgage_id',
    'condition' => 'is_primary=1'
 ),

// primary applicant info
'primaryApplicant' => array(self::HAS_ONE, 'Person', 'person_id', 
    'through' => 'primaryApplicantConnection'),

// co-applicant connection
'coApplicantConnection' => array(self::HAS_MANY, 'PersonToMortgage', 'mortgage开发者_开发知识库_id',
    'condition' => 'is_primary<>1 OR is_primary IS NULL'
),

// co-applicants' info
'coApplicants' => array(self::HAS_MANY, 'Person', 'person_id',
    'through' => 'coApplicantConnection'
),

In Mortgage Controller,

$mortgage_model=$this->loadModel($id);
$primaryApplicant = $mortgage_model->primaryApplicant; // return expect result
$coApplicants = $mortgage_model->coApplicants; // the problem is here

When I want to get all the coApplicants by using $mortgage_model->coApplicants, the result also includes primary applicant.

To track the problem down, I tried this $mortgage_model->coApplicantConnection which only return co-applicant rows.

So I wonder where primary applicant coming from ? and how it ends up in $mortgage_model->coApplicants ? is it a bug ?


It seems like what's happening is if you are using the default "loadModel($id)" function, it uses "findByPk", which will only return one result based on the primary key, presumably in your case the primary applicant, regardless of other conditions. You need to create the model in a way that uses the conditions and returns more than one row with something like:

$model = Mortgage::model()->findAll();

and then apply the relation to that result.

0

精彩评论

暂无评论...
验证码 换一张
取 消