【问题标题】:Laravel Eloquent Relationship For Multiple tables多个表的 Laravel Eloquent 关系
【发布时间】:2019-06-23 15:06:40
【问题描述】:
我的数据库中有 3 个表:Users、Biodata、Roles。
Users 和 Roles 与数据透视表 role_user 相关。
Users 具有角色student & employer。
我希望所有具有student 角色的用户也具有biodata。
我尝试了很多次,但找不到解决方案。希望大家帮帮我
$users = User::with('roles')->with('biodata')->get();
【问题讨论】:
标签:
laravel
eloquent
relationship
【解决方案1】:
试试这个:
$users = User::with('biodata')->whereHas('roles', function($query) {
$query->where('name', 'student');
})->get();
【解决方案2】:
使用 whereHas ,它用于实际的 where 查询。
$users = User::whereHas('roles', function ($query) {
$query->where('name', '=', 'student');
})->with('biodata')->get();
【解决方案3】:
你正在寻找这个:$user = User::with('roles', 'biodata')->get();