[英]Laravel 5.4 Query DB with pivot table
So, I have the following Tables named: 因此,我将以下表命名为:
ALBUMS(id, name, shared, group_id, user_id)
GROUPS(id, name, user_id)
GROUP_USER(group_id, user_id)
What I want to do is, using Laravel Eloquent to get the results of a query by checking if the AUTHENTICATED user is a member of the GROUP owned by the ALBUM. 我想要做的是使用Laravel Eloquent通过检查AUTHENTICATED用户是否是ALBUM拥有的GROUP的成员来获取查询结果。
Album Model: 专辑型号:
public function groupSecurity()
{
return $this->belongsTo(Group::class, 'group_id');
}
Group Model: 组型号:
public function ownedBy()
{
return $this->belongsTo(User::class, 'user_id');
}
public function members()
{
return $this->belongsToMany(User::class, 'group_user');
}
Thank you for your help :) 谢谢您的帮助 :)
You can do like this: 您可以这样:
$album = Album::whereHas('groupSecurity', function ($query) {
$query->whereHas('members', function($query2){
$query2->where('user_id', auth()->user()->id);
})->where('user_id', auth()->user()->id);
})->first();
So you search for one album that has a groupSecurity
which has in his members
the auth user and also it's owned
by the auth user. 因此,您搜索一个具有groupSecurity
相册,该groupSecurity
的members
具有auth用户,并且该用户也由auth用户owned
。 If a record match this conditions $album
will have an instance of Album model, if not it will be null so you can do: 如果一条记录与该条件匹配,则$album
将具有一个Album模型的实例,否则,它将为null,因此您可以执行以下操作:
if($album){
// AUTHENTICATED user is a member of the GROUP owned by the ALBUM
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.