在laravel枢轴桌上过滤的雄辩方式

时间:2016-02-15 20:34:54

标签: laravel laravel-5 eloquent

以下查询适用于检索所有约会及其关联的客户和用户。

    $appointments = Appointment::with('client', 'user')
    ->where('appointments.business_id', '=', \Auth::user()->business_id )
    ->orderBy('appointments.start', 'ASC')
    ->get();

添加以下条件以选择约会的语法是什么:

where users.id = \Auth::user()->id

我认为添加以下行会起作用,但它没有:

->where('users.id', '=', \Auth::user()->id )

由于

1 个答案:

答案 0 :(得分:0)

因为在约会表中找不到users.id列 你不能在它上面执行直接的where子句。 whereHas方法允许您向关系约束添加自定义约束。请查看https://laravel.com/docs/5.2/eloquent-relationships#querying-relations了解详情。

  $userId = \Auth::user()->id;

  $appointments = Appointment::with('client', 'user')
   ->whereHas('user',function($query) use($userId)
   {
     $query->where('users.id,'=',$userId);

  })
  ->where('appointments.business_id', '=', \Auth::user()->business_id )
  ->orderBy('appointments.start', 'ASC')
  ->get();
相关问题