Laravel Eloquent 有没有更好的方法来编写这个查询?
Laravel Eloquent is there a better way to write this query?
我有一个典型的枢轴 table 结构,如下所示:
用户
id [...]
地点
id [...]
User_Location
编号 | user_id | location_id
我需要获取当前授权用户可以访问的位置,然后我需要获取也可以访问所有这些位置的所有用户。
我试图找出一种“eloquent”的方法来做到这一点,但我对它还不够熟悉。这行得通,但我想知道这是否是最好的方法?
$locations = auth()->user()->locations(); //returns the user_location records
$locationIds = $locations->pluck('location_id');
$locationUsers = new UserLocation();
$userIds = $locationUsers->whereIn('location_id', $locationIds)->groupBy('user_id')->pluck('user_id');
$users = User::withTrashed()
->whereIn('id', $userIds)
->get();
return view('users.index')->with('users', $users);
这是代码中引用的 locations()
关系:
public function locations()
{
return $this->belongsToMany(Location::class, 'user_location')->withPivot('primary');
}
您必须在 Locations 模型中创建一个新方法。
public function users()
{
return $this->belongsToMany(User::class, 'user_location');
}
那么您的查询可能如下所示。
$locations = auth()->user()->locations()->with('users')->get();
$users = $locations->pluck('users');
如果您需要获取所有用户 withTrashed
那么您应该为此修改第一行。
$locations = auth()->user()->locations()->with(['users' => function ($user) {
$user->withTrashed();
}])->get();
我有一个典型的枢轴 table 结构,如下所示:
用户
id [...]
地点
id [...]
User_Location
编号 | user_id | location_id
我需要获取当前授权用户可以访问的位置,然后我需要获取也可以访问所有这些位置的所有用户。
我试图找出一种“eloquent”的方法来做到这一点,但我对它还不够熟悉。这行得通,但我想知道这是否是最好的方法?
$locations = auth()->user()->locations(); //returns the user_location records
$locationIds = $locations->pluck('location_id');
$locationUsers = new UserLocation();
$userIds = $locationUsers->whereIn('location_id', $locationIds)->groupBy('user_id')->pluck('user_id');
$users = User::withTrashed()
->whereIn('id', $userIds)
->get();
return view('users.index')->with('users', $users);
这是代码中引用的 locations()
关系:
public function locations()
{
return $this->belongsToMany(Location::class, 'user_location')->withPivot('primary');
}
您必须在 Locations 模型中创建一个新方法。
public function users()
{
return $this->belongsToMany(User::class, 'user_location');
}
那么您的查询可能如下所示。
$locations = auth()->user()->locations()->with('users')->get();
$users = $locations->pluck('users');
如果您需要获取所有用户 withTrashed
那么您应该为此修改第一行。
$locations = auth()->user()->locations()->with(['users' => function ($user) {
$user->withTrashed();
}])->get();