0
我想从数据库查询中访问数据,我认为这需要一个连接。我拥有的用户可以与众多小组分开。我正在使用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的用户属于具有的1和2的id是什么,我试图做的就是抓住所有的数据库中谁 属于名为admin将USER_GROUP用户的user_groups 。所以,我想这样的事情
DB::table('users')->select('userName')
->join('user_groups', 'users_user_groups')
->where('name', '=', 'admin')->get();
这个我知道全错了,我怎么能使用belongsToMany和数据透视表时,得到一组内的所有用户?
谢谢