I’m very new to CakePHP. I want to do a query in my database like this
SELECT m.id, l.*, lp.picture_path
FROM member m INNER JOIN listing l ON m.member_id = l.member_id
INNER JOIN listingPicture lp ON l.listing_id = lp.listing_id
WHERE lp.picture_default='1'
I have 3 models in my cakephp : Member, Listing, and ListingPicture each with the following relationship
- Member hasMany Listing
- Listing hasMany ListingPicture
- Listing belongsTo Member
- ListingPicture belongsTo Listing
From my Member controller how do I execute the query above ?
I’ve tried
$this->Member->Listing->find("all")
… which works well but when I added a conditions like this:
$this->Member->Listing->find('all', array(
'conditions' => array('ListingPicture.picture_default'=>'1')));
… I get an error.
Because I’m new to CakePHP, I don’t know how to see the error.
Can anyone advise me how I can perform this query?
Make sure to set your model as:
Then use CakePHP’s containable behavior to include only the associated data you want, with specified fields and conditions.
To follow with the MVC concept, it’s suggested to keep your finds in a Model as opposed to a controller. It’s not required, but – it makes it much easier to know exactly where all finds are, and keeps with the “Fat model / Skinny controler” mantra. In this case, it’d be something like: