如何在With()中编写子查询?

时间:2019-04-12 07:19:09

标签: laravel eloquent

我必须获取特定数据,例如“角色”表已提交状态,并且我需要状态 = 1才能从角色表获取所有数据

$result = User::select()
    ->with('roles')
    ->where('email', $email)
    ->get();
    return $result;

2 个答案:

答案 0 :(得分:3)

遵循以下问题的答案:Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? 如果我正确理解您的数据模型的结构,则:

  • 用户具有许多角色
  • 角色具有财产状态
  • 要按状态= 1过滤
$users = User::whereHas('roles', function($q){
    $q->where('status', '1');
})
->where('email', $email)
->get();

编辑:我不满意上面的答案,因为据我所知,在那种情况下,返回的用户尚未加载角色列表,因此我检查了文档(https://laravel.com/docs/5.8/eloquent-relationships)并给出了我发现的内容如下,应该按照您的要求进行操作:

$users = User::with(['roles' => function ($query) {
    $query->where('status', '1');
}])
->where('email', $email)
->get();

我从没用过雄辩的语言,也不是php开发人员,所以我不能尝试使用此代码段,如果不正确,请告诉我。

答案 1 :(得分:2)

您可以编写

这样的子查询
$result = User::select()
    ->with(['roles' => function($q){    
         $q->where('status', 1);
    }])
    ->where('email', $email)
    ->get();
    return $result;
相关问题