【问题标题】:Joining pivot table to access data加入数据透视表以访问数据
【发布时间】:2016-06-09 14:23:33
【问题描述】:

我正在尝试从我认为需要连接的数据库查询中访问数据。我的用户可以属于许多组。我正在使用 belongsToMany 关系。我的模特是这样的

class User extends Model
{
    protected $table = 'users';
    protected $guarded = [];

    public function group()
    {
        return $this->belongsToMany('App\Group', 'users_user_groups')->withPivot('user_id', 'group_id');
    }
}

class Group extends Model
{
    protected $table = 'user_groups';
    protected $guarded = [];
    use SoftDeletes;

    public function user()
    {
        return $this->belongsToMany('App\User', 'users_user_groups')->withPivot('user_id', 'group_id');
    }
}

当我也运行我需要的一切时,我可能会得到如下数据。

users
+----+---------------+
| id | name          | 
+----+---------------+
| 1  | John Doe      |    
+----+---------------+

user_groups
+----+---------------+-----------------+
| id | name          | description     | 
+----+---------------+-----------------+
| 1  | Group AA      | Something       |    
+----+---------------+-----------------+
| 2  | Group BB      | Something       |    
+----+---------------+-----------------+

users_user_groups
+----+---------------+-----------------+
| id | user_id       | group_id        | 
+----+---------------+-----------------+
| 1  | 1             | 1               |    
+----+---------------+-----------------+
| 2  | 1             | 2               |    
+----+---------------+-----------------+

所以我知道 id 为 1 的用户属于 id 为 1 和 2 的 user_groups。我要做的是抓取我的数据库中的所有用户 属于名为 admin 的 user_group。所以我正在尝试这样的事情

DB::table('users')->select('userName')
    ->join('user_groups', 'users_user_groups')
    ->where('name', '=',  'admin')->get();

我知道这都是错误的,我如何在使用 belongsToMany 和数据透视表时获取组内的所有用户?

谢谢

【问题讨论】:

    标签: laravel laravel-5


    【解决方案1】:

    Eloquent 使用关系,而不是查询构建器。

    您可以通过执行以下操作来实现您的目标:

    $group = Group::where('name', 'admin')->first();
    $users = $group->users; // Where users is the name of your relationship (At the moment you have user)
    

    在底层,它将执行两个 SQL 语句并将它们映射到 eloquent 对象中,而不是连接。语句将如下所示:

    select * from user_groups where name = ? and deleted_at is not null limit 1
    select * from users where id in (?, ?)
    

    当您有一个实例Group 时,您可以通过调用它来执行关系,就好像它是一个属性一样。所以在那之后$users 将包含User 实例的集合,所以你可以循环它们:

    foreach ($users as $user) {
        // Do something with $user
    }
    

    【讨论】:

      猜你喜欢
      • 2022-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多