【问题标题】:Laravel 4 Eloquent table join and where clause on multiple tablesLaravel 4 Eloquent 表连接和多个表上的 where 子句
【发布时间】:2023-03-28 07:50:01
【问题描述】:

您好,我正在使用 Laravel 和 Eloquent 来存储用户、个人资料和分配的角色。我的表结构如下;

users

id | username | email | password | created_at | updated_at

profiles

id | user_id | firstname | created_at | updated_at 

roles 

id | name 

assigned_roles 

id | user_id | role_id

我正在尝试选择角色名称等于 admin 的所有用户。但是当我执行以下操作时,我得到一个空数组:

 return \User::with('profile')->join('assigned_roles', function ($join) {
        $join->where('assigned_roles.user_id', '=', 'users.id');
    })->get();

任何想法我做错了什么?

我也在使用 Zizaco Entrust and Confide https://github.com/Zizaco/entrust/tree/1.0

【问题讨论】:

  • @trincot 不,这是正确的。我在 app/models/User.php 中有一个定义关系的函数
  • 只是为了确保...您在“assigned_roles”中为您的用户定义了角色?如果没有对应的行,则不会返回任何结果。
  • @jedrzej.kurylo 我没有这个模型我正在使用github.com/Zizaco/entrust/tree/1.0,但它没有这样做的功能
  • 好的,但是“assigned_roles”表中有数据吗?
  • 是的,有数据表明@jedrzej.kurylo

标签: php laravel join laravel-4 eloquent


【解决方案1】:

为了获取具有 admin 角色的用户,您需要使用 Eloquent 的 whereHas() 方法:

$admins = \User::with('profile')
  ->whereHas('assigned_roles', function($query) {
    $query->whereName('admin');
  })
  ->get();

我假设您定义了 assigned_roles 关系。如果没有,请在您的用户和角色之间添加多对多关系:

public function assigned_roles() {
  return $this->belongsToMany('\Your\Model\Namespace\Role', 'assigned_roles', 'user_id', 'role_id');
}

【讨论】:

  • 我收到此错误Call to undefined method Illuminate\Database\Query\Builder::assigned_roles() 我没有assigned_roles 模型。只是一个名为assigned_roles 的表,角色的名称保存在roles 表中。
  • 您是否在您的用户模型中定义了这种关系?您需要在角色和用户之间添加多对多关系
  • 不,我没有。角色名称也保存在角色表中。我的数据库架构发布在问题中:)
  • 然后定义关系 - 否则 Eloquent 将不知道如何链接用户及其角色。如果模型没有发布,数据库结构将毫无用处,因为它们包含 Eloquent 所知道的关于您的模型的所有信息,而不是数据库架构。
  • 我将如何定义我上面的架构的雄辩关系?抱歉,只是我很困惑,我尝试了一些组合都不起作用。基本上一个用户可以有很多角色。但这是通过assigned_roles 分配的,它有一个user_id 和role_id。我已经说过用户 hasOne->('Profile');欢迎任何帮助!
猜你喜欢
  • 2019-11-27
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
相关资源
最近更新 更多