如何使用具有急切加载的条件从第二个模型检索数据

时间:2018-02-03 07:32:38

标签: mysql laravel laravel-5 eloquent

我不确定这个问题的标题是否正确。我有两个型号。 eventdatesbookedslots。事件日期与hasManybookedslots 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

的位置

我怎样才能实现它?先感谢您。

1 个答案:

答案 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.