dennysutanto
dennysutanto

Reputation: 23

Cakephp complex hasMany relationship query

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

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?

Upvotes: 0

Views: 1302

Answers (2)

Dave
Dave

Reputation: 29121

Make sure to set your model as:

public $actsAs = array('Containable');

Then use CakePHP's containable behavior to include only the associated data you want, with specified fields and conditions.

$this->Member->Listing->find('all', array(
    'fields' => array('*'),
    'contain' => array(
        'Member' => array(
            'fields' => array('id')
        )
        'ListingPicture' => array(
            'conditions' => array('ListingPicture.picture_default' => '1')
            'fields' => array('picture_path')
        )
    )
));

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:

//in the Member Controller
$listings = $this->Member->Listing->getListings();

//in the Listing Model
function getListings() {
    $listings = $this->find('all', ...
    return $listings;
}

Upvotes: 1

Mohammed H
Mohammed H

Reputation: 7048

You should give the condition at the time of binding ListPicture to Listing.

$this->Member->Listing->bindModel(array(
  'ListPicture'=>array(
    'condtions'=>array('ListingPicture.picture_default'=>'1')
  ))
);

Upvotes: 0

Related Questions