0

My Reservation Model hasAndBelongsToMany Profile Model. I want to find Profiles using Reservation.item_id = $id When I get the data, the data show all the datas in Profile.

$profiles = $this->Profile->find('all', array(  
        'contain' => array(
            'Reservation' => array(
                'conditions' => array('Reservation.item_id' => $id)
            )
        ),
        'order' => 'Profile.order ASC'
    ));
print_r($profiles); 

What is the matter????????...

지윤김
  • 17
  • 5
  • When you say it shows all the data in Profile are you only looking for a sub set of the data like the name? Or do you mean that you are trying to return only profiles that have the reservation with matching ID and yet ALL profiles are being returned even if they don't have a matching reservation. – KaffineAddict Jan 25 '18 at 21:18
  • I'm trying to return only profiles that have the reservation and the item_id of the reservation should be $id – 지윤김 Jan 25 '18 at 21:39
  • Please check my answer and see if that solves your problem. – KaffineAddict Jan 26 '18 at 00:49

2 Answers2

1

To find entities by associated model data, you can use matching():

$profiles = $this->Profiles->find()
    ->contain(["Reservations"])
    ->matching("Reservations",function($q) use ($id) {
        return $q->where(["Reservations.item_id" => $id]);
    })
    ->all();

More about matching(): Filtering by associated data

Szymon
  • 1,385
  • 1
  • 8
  • 10
0

Assuming you mean that you are getting back all profiles even when all you want is only a sub set of profiles that have a reservation for the proper item then what you need to do is something like the query that follows.

$profiles = $this->Profile->Reservation->find('all', array(  
    'contain' => array(
        'Profiles'
    ),
    'conditions' => array('item_id' => $id),
    'order' => 'Profile.order ASC'
);

What you are saying in your query is find all profiles and include any reservations that match the item ID.

What the query I posted is saying is find all matching reservations and then include their associated profiles.

KaffineAddict
  • 436
  • 2
  • 11