我有两个型号User
and Profile
处于一对一的关系中。
我想检索所有用户所在位置profile.status == TRUE
使用以下代码。
$users = User::with(['profile' => function ($query) {
$query->where('status', TRUE);
}])->get();
dd(count($users)); //50
我有 50 个用户,其中只有 3 个有status == TRUE
。但总是显示50.
您将获得 50 个用户,因为您将条件应用于profile
. dd($user->profile)
您将仅获得状态为 true 的个人资料的记录。
Use whereHas()
:
$users = User::whereHas('profile', function ($query) {
$query->where('status', TRUE);
})->get();
dd(count($users));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)