【问题标题】:Fetch data from two Table with where condition in Laravel 5.6在 Laravel 5.6 中使用 where 条件从两个表中获取数据
【发布时间】:2018-08-16 19:51:49
【问题描述】:

我想从两个表配置文件和用户中获取数据,它们与一对一关系链接我从两个表中获取数据,但现在我想在用户表中添加该列的 where 条件。 此代码可以正常获取数据。

        $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 条件,我使用上面的查询成功地从两个表中获取数据

标签: php mysql database laravel laravel-5.6


【解决方案1】:

您可以在查询关系或关系本身中添加 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();

【讨论】:

  • 使用上面的代码,他们没有从第二个表中获取数据。就像我想获取用户电子邮件和服务名称一样,他们的个人资料属于该表。
【解决方案2】:

如果您使用关系表获取数据并在查询中使用 where 条件,请编写此代码,它 100% 对我有用。

Profile::join('users', function($join){
        $join->on('profiles.user_id', '=', 'users.id')
        ->where('users.role_id', '=', 3);
    })
    ->get();

使用连接,我成功获取了用户角色 id 等于 3 的所有配置文件以及其他关系表数据,例如来自用户表的电子邮件和来自服务表的服务标题以及来自配置文件表的所有数据

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2013-05-17
    • 2014-02-18
    • 1970-01-01
    相关资源
    最近更新 更多