我在根據位置顯示用戶時遇到問題,
我的問題是它只顯示用戶,而不是與位置關聯的用戶
我希望用戶只向他顯示它在表中鏈接的位置中的用戶(location_user)
我知道問題出在 location_user'、'location_user.user_id'、'='、'users.id'
但我希望鏈接是智能的,我不想在用戶串列中添加名為 location_id 的列
因為我想要多個位置
這是 UsersController.php 的資料
$data = User::leftjoin('location_user', 'location_user.user_id', '=', 'users.id')
->where('location_user.user_id', auth()->user()->id)
->leftjoin('locations', 'locations.id', '=', 'location_user.location_id')
->where('locations.status', '1')
->select('users.*',)
->orderBy('status', 'DESC')->get();
表
用戶: https ://i.stack.imgur.com/h3dID.jpg
location_user: https ://i.stack.imgur.com/6KGZN.jpg
地點: https ://i.stack.imgur.com/UDbDJ.jpg
誰能幫我?
謝謝。
uj5u.com熱心網友回復:
根據您的表結構 - User和Location通過location_user資料透視表存在多對多關系。
如果在兩個模型上都定義了各自的關系,例如
//User Model
public function locations()
{
return $this->belongsToMany(Location::class);
}
//Location Model
public function users()
{
return $this->belongsToMany(User::class);
}
然后您可以撰寫一個查詢來獲取與登錄用戶的位置相關聯的所有用戶
$locationIds = auth()->user()->locations->pluck('id');
$users = User::query()
->whereHas('locations', fn($query) => $query->whereIn('id', $locationIds)
/** If you want results to include the currently logged in user
* remove the below where condition **/
->where('id', '<>', auth()->id())
->get();
或使用傳統的匿名閉包函式而不是箭頭函式語法
$locationIds = auth()->user()->locations->pluck('id');
$users = User::query()
->whereHas('locations', function($query) use($locationIds){
$query->whereIn('id', $locationIds);
})
/** If you want results to include the currently logged in user
* remove the below where condition **/
->where('id', '<>', auth()->id())
->get();
uj5u.com熱心網友回復:
首先,您不需要關聯表“location_user”,因為您的用戶只與一個位置相關聯,因此您在這里有一個 MenyToOne 關系,您可以通過將這些行添加到您的模型來實作:
class User extends Model
{
//here
public function location()
{
return $this->belongsTo(Location::class);
}
}
class Location extends Model
{
//here
public function users()
{
return $this->hasMany(User::class);
}
}
之后,您可以通過 id 查詢鏈接到用戶的位置中的成員,如下所示:
$user = User::find(1); //get user by id : 1
$location = $user->location // get location associted with user id 1
$members = $location->users // get all members associated with the location of user id 1
如果是ManyToMany關系,你仍然可以使用相同的方法,只需修改:
/*
public function location()
{
return $this->belongsTo(Location::class);
}
*/
經過 :
public function locations()
{
return $this->belongsToMany(Location::class,'location_user');
}
和 :
/*
public function users()
{
return $this->hasMany(User::class);
}
*/
經過 :
public function users()
{
return $this->belongsToMany(User::class,'location_user');
}
在您可以通過集合方法合并成員之后:集合 或使用 whereHas 和 orHas
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/486459.html
