Hkm Sadek
Hkm Sadek

Reputation: 3209

How to retrieve data from second model using where condition with eager loading

I am not sure if the title is correct for this question. I have two models. eventdates and bookedslots. Event date has a hasMany relation with bookedslots and bookedslots belongsTo eventdates relation.

I am running this query now

Eventdate::select('eventDate','id')
  ->with(array('slot'=> function($q) use ($userData){
    $q->select('id', 'eventdate_id','user_id','slot')->where('bookedFor',$userData[0]->id); 
  // Here I want to limit the slots(bookedaslot) model that is has event date and also user id. 
  }))
  ->with(array('slot.user'=> function($q) use ($userData){
    $q->select('id', 'name','profilePic','userName');
  }))
 ->orderBy('created_at', 'asc')->get();

Here is how my data looks in mysql.

bookedFor | slot | eventdate_id

1 | A | 1

2 | A | 1

2 | B | 1

Currently the query returns all 3 but I want to return only where bookedFor=2

How can I achieve it? Thank you in advance.

Upvotes: 0

Views: 37

Answers (1)

user320487
user320487

Reputation:

All you should need is a with clause and then subquery on the user's id like:

$userId = 2;
Eventdate::with(['slot' => function ($query) use ($userId) {
    $query->with('user')->where('bookedFor', $userId)
}])->orderBy('created_at', 'asc')->get();

That will only return slots that belong to the eventdate and then only select those for which bookedFor matches the user id.

Upvotes: 1

Related Questions