我很难根据地点向用户展示,
我的问题是它只显示用户,而不显示用户与位置的关联
我希望用户只向他展示在表中链接的位置上的用户(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
有谁可以帮我?
谢谢。
发布于 2022-06-05 06:06:13
根据您的表结构-有一个多到多关系用户和位置通过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();发布于 2022-06-05 01:37:52
首先,您不需要将表"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://stackoverflow.com/questions/72503880
复制相似问题