2

I have three models that are as follows:

Location hasMany SportType hasMany Sport, then Sport belongsTo SportType belongsTo Location

In the SportType model, the belongsTo Location has a condition 'Location.status' => true, such that it only retrieves records where the Location status is true. Works fine.

When retrieving records via a plain old find() in the Sport model, I would assume that it would not return records where the associated SportType's associated Location was false, but that is not the case.

I believe I could use containable behavior or explicitly constructed joins in my controller to get what I want, but I'm wondering if this is something I can achieve purely through the model relationships. Perhaps not.

drpudding
  • 159
  • 4
  • 14

1 Answers1

1

You can either use Joins or change the model you're doing the search on and do it through the restricting model (ie Location).

$this->Location->find('all', array(
    'conditions' => array(
        'Location.status' => true
    ),
    'contain' => array(
        'SportType' => array(
            'Sport'
        )
    )
));

But you cannot narrow the results of the searching model based on conditions within contained models.

Update:

Joins also allow you to add more conditions to other models...etc, as opposed to Contain which does not, so I supposed I'd lean toward going with Joins as that leaves you more flexibility moving forward.

Also, a JOIN will do one more-complicated query, while a contain will do many simpler queries... so depending on your database structure, that could be considered.

Bottom line, it's preference - both are just fine and whichever works for you is great.

Dave
  • 28,833
  • 23
  • 113
  • 183
  • Ah, I see. Thanks for the clarification. Is either method considered superior? As I am listing all Sports, I was thinking of deriving this through the Sport model and sport/index route. But I now see it could be something like location/list_sports. I am new to cakePHP, and just trying to get my head around it. – drpudding Feb 16 '13 at 06:34