开发者

CakePHP - Find conditions for related model

I have SubjectGroup, which hasMany Subject.

class SubjectGroup extends AppModel {

    public $hasMany = array(
        'Subject' => array('order' => 'Subject.name')
    );

}

class Subject extends AppModel {

    public $belongsTo = array('SubjectGroup');

}

I want to get all SubjectGroups, and recursively retrieve their Subjects, but only the Subjects that have a status of 2. I can't figure out how to do this.

$subjectGroups = $this->SubjectGroup->find('all', array(
    'conditions' => array('Subject.status !=' => 2),
    'order' => 'SubjectGroup.name'
));

Warning (512): SQL Error: 1054: Unknown column 'Subject.status' in 'where clause'

Note: I hav开发者_运维百科e read that I can add a conditions array to the model relationship definition, but I don't want the relationship to always use the condition. Sometimes I will want to just retrieve the SubjectGroups and Subjects with status 2, and sometimes the SubjectGroups with all Subjects, regardless of their status.

PROGRESS

With some help from Ross, I now am trying to use the Containable behaviour. I have this so far:

$this->SubjectGroup->find('all', array(
    'contain' => 'Subject.status != 2',
    'order' => 'SubjectGroup.name'
));

There are no errors, but it returns all Subjects, even the ones with status = 2.


What you're doing is asking Cake to look for the field status in the SubjectGroup table. It doesn't exist.

What you really want to do is use containable behaviour, and access the status field this way.

Try this:

$this->SubjectGroup->Behaviors->attach('Containable');

$subjectGroups = $this->SubjectGroup->find('all', array(
    'contain'=>array('Subject'=>array(
                             'conditions' => array('Subject.status !=' => 2))
                    ),
    'order' => 'SubjectGroup.name'
    ));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜