Laravel eloquent - 多对多,选择只匹配多表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19939145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:39:19  来源:igfitidea点击:

Laravel eloquent - Many to Many, select only matching the many table

laravellaravel-4eloquent

提问by Rich Bradshaw

I have 3 tables describing users, roles and role_user. These look like this:

我有 3 个表来描述用户、角色和角色用户。这些看起来像这样:

users -> id, name
roles -> id, name
role_user -> user_id, role_id

In my User class I have:

在我的 User 类中,我有:

public function roles()
{
    return $this->belongsToMany('Role');
}

The aim here is of course to allow a user to have multiple roles.

这里的目的当然是允许用户拥有多个角色。

I can do a query like User::with('roles')->get()which works fine.

我可以做一个像User::with('roles')->get()这样工作正常的查询。

What I want though is only to select users that have a certain role, ideally specified by name, but it could be by ID instead if needed. How do I do this using Eloquent?

我想要的只是选择具有特定角色的用户,最好按名称指定,但如果需要,也可以按 ID 指定。我如何使用 Eloquent 做到这一点?

回答by tharumax

Write a belongsToManyrelationship in RoleModel

belongsToManyRole模型中写入关系

    class Role extends Eloquent {
        public function users() {
            $this->belongsToMany('Users');
        }
    }

Then use Following Eloquent Query.

然后使用Follow Eloquent Query。

    $role = Role::with('users')->whereName($name)->first();

You can access all users that have $namerole as $role->users.

您可以访问所有$name角色为 的用户$role->users

回答by Mathius17

The answer by tharumaxis completely valid and extremely useful. The only problem is if you want to run the query with other things. Let's say, the users that have an adminrole and signed up before 2014. Or if you want to use it as a scope, you can't do it his way.

tharumax的回答是完全有效且非常有用的。唯一的问题是如果你想用其他东西运行查询。假设有admin角色并在 2014 年之前注册的用户。或者如果您想将其用作范围,则不能按他的方式进行。

This is another way but directly on the query (though this one searches by id):

这是另一种方式,但直接在查询上(尽管这个是按 id 搜索的):

User::join('role_user', 'users.id', '=', 'role_user.user_id')
      ->where('role_user.role_id',$id)->get();

If you want, you could create a scope for easier syntax and management. e.g I want to get the users with role admin.

如果需要,您可以创建一个范围以简化语法和管理。例如,我想获得具有角色的用户admin

Scope:

范围:

// Inside User model

public function scopeAdmins($query)
{
  return $query->join('rol_user', 'users.id', '=', 'rol_user.user_id')
               ->where('rol_user.rol_id', id_of_admin );
}

Then you could easily retrieve all the adminusers doing this (and add other conditions if you need to):

然后,您可以轻松检索所有admin执行此操作的用户(并根据需要添加其他条件):

User::admins()->get();