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, usi...

问题:

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.

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 :)


回答1:

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. If a record match this conditions $album will have an instance of Album model, if not it will be null so you can do:

if($album){
    // AUTHENTICATED user is a member of the GROUP owned by the ALBUM
}
  • 发表于 2019-02-21 13:07
  • 阅读 ( 171 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除