1

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 have 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.

BadHorsie
  • 14,135
  • 30
  • 117
  • 191

1 Answers1

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'
    ));
Ross
  • 18,117
  • 7
  • 44
  • 64
  • Yep, Containable looks like what I need, but your code didn't work. According to the manual, it has an example of `$this->Post->find('all', array('contain' => 'Comment.author = "Daniel"'));` So I tried modifying it to `$this->SubjectGroup->find('all', array('contain' => 'Subject.status != 2', 'order' => 'SubjectGroup.name'));` but that doesn't work. – BadHorsie Oct 05 '11 at 16:46
  • Can you post your associations? And what didn't work? error, unexpected data? – Ross Oct 05 '11 at 17:41
  • See my updated main post. No errors, it just returns all Subjects so the containable behaviour doesn't appear to be doing anything. – BadHorsie Oct 06 '11 at 09:14
  • 4
    This answer should not be accepted, since it returns ALL SubjectGroups, but each of them only includes Subjects with status != 2. – Vanja D. Jul 07 '13 at 17:51
  • Yes! I am agree with Vanja D. – bhushya Jul 04 '15 at 17:59