简体   繁体   中英

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.

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. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM