我必须获取特定数据,如“角色”表已归档状态,我需要状态 = 1,所有数据都来自角色表
$result = User::select()
->with('roles')
->where('email', $email)
->get();
return $result;
最佳答案
按照这个问题的答案: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();
我从来没有使用过 eloquent 和 laravel,我也不是 php 开发人员,所以我无法尝试这个片段,如果不正确请告诉我。
关于laravel - With()中如何写子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55646422/