使用 Laravel 5.6 中的 where 条件从两个 Table 中获取数据
Fetch data from two Table with where condition in Laravel 5.6
我想从两个 table 配置文件和用户中获取数据,他们是 link 一对一关系 我从两个 table 中获取数据,但现在我想添加用户 table 中的列的条件。
此代码可以很好地获取数据。
$clients = Profile::all();
return view('admin.clients', compact('clients'));
但我想要这样的东西。
'select profile.*, user.* from profile, user where profile.user_id=users.id and users.role_id=3';
如何将此查询转换为上述查询的形式。
您可以在查询关系或关系本身中添加 where。
假设您有一个用户关系,您可以这样做
Profile::with(['users' => function($users) {
$users->where('role_id','=',3);
}])->get();
这将为您获取所有配置文件,并筛选出这些配置文件中角色 = 3 的用户。
如果您想要获取角色 = 3 的用户的配置文件,那么您可以使用 whereHas
Profile::with('users')->whereHas('users', function($users) {
$users->where('role_id','=',3);
})
->get();
如果您使用关系 table 获取数据并在查询中使用 where 条件,请编写此代码,它 100% 适合我。
Profile::join('users', function($join){
$join->on('profiles.user_id', '=', 'users.id')
->where('users.role_id', '=', 3);
})
->get();
使用加入我成功获取了所有用户角色 ID 等于 3 的配置文件以及其他关系 tables 数据,例如来自用户 table 的电子邮件和来自服务 table 的服务标题使用配置文件 table
中的所有数据
我想从两个 table 配置文件和用户中获取数据,他们是 link 一对一关系 我从两个 table 中获取数据,但现在我想添加用户 table 中的列的条件。 此代码可以很好地获取数据。
$clients = Profile::all();
return view('admin.clients', compact('clients'));
但我想要这样的东西。
'select profile.*, user.* from profile, user where profile.user_id=users.id and users.role_id=3';
如何将此查询转换为上述查询的形式。
您可以在查询关系或关系本身中添加 where。
假设您有一个用户关系,您可以这样做
Profile::with(['users' => function($users) {
$users->where('role_id','=',3);
}])->get();
这将为您获取所有配置文件,并筛选出这些配置文件中角色 = 3 的用户。
如果您想要获取角色 = 3 的用户的配置文件,那么您可以使用 whereHas
Profile::with('users')->whereHas('users', function($users) {
$users->where('role_id','=',3);
})
->get();
如果您使用关系 table 获取数据并在查询中使用 where 条件,请编写此代码,它 100% 适合我。
Profile::join('users', function($join){
$join->on('profiles.user_id', '=', 'users.id')
->where('users.role_id', '=', 3);
})
->get();
使用加入我成功获取了所有用户角色 ID 等于 3 的配置文件以及其他关系 tables 数据,例如来自用户 table 的电子邮件和来自服务 table 的服务标题使用配置文件 table
中的所有数据