我不确定这个问题的标题是否正确。我有两个型号。
eventdates
和bookedslots
。事件日期与hasMany
和bookedslots
belongsTo bookedslots
关系具有eventdates
关系。
我现在正在运行此查询
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();
以下是我的数据在mysql中的显示方式。
预订为|插槽| eventdate_id
1 | A | 1
2 | A | 1
2 | B | 1
目前查询返回全部3但我想仅返回visitedFor = 2
的位置我怎样才能实现它?先感谢您。
答案 0 :(得分:1)
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.