【发布时间】:2019-09-02 21:52:40
【问题描述】:
我必须获取特定数据,例如“角色”表已提交 status,并且我需要 status = 1 以便所有数据都从角色表中获取
$result = User::select()
->with('roles')
->where('email', $email)
->get();
return $result;
【问题讨论】:
我必须获取特定数据,例如“角色”表已提交 status,并且我需要 status = 1 以便所有数据都从角色表中获取
$result = User::select()
->with('roles')
->where('email', $email)
->get();
return $result;
【问题讨论】:
按照这个问题的答案:Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean? 如果我正确理解了您的数据模型的结构:
$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 开发者,所以我无法尝试这个 sn-p,如果不正确请告诉我。
【讨论】:
你可以像这样写子查询
$result = User::select()
->with(['roles' => function($q){
$q->where('status', 1);
}])
->where('email', $email)
->get();
return $result;
【讨论】: