【发布时间】: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 和数据透视表时获取组内的所有用户?
谢谢
【问题讨论】: