简体   繁体   中英

Return multiple relationships with Laravel Eloquent

在此处输入图像描述 I have a table called users and user have different roles the relation in table

  • role_users (id,user_id,role_id)

now a role have different permissions for different resources

  • permissions(id,name) (permissions: edit,create)
  • resources(id,name) (resources: post,comment,user)

The relation of role with permission

  • role_resource_permissions (id,role_id,permission_id,resource_id)

What I want is to do an Eloquent Query to search available permissions with the resource for the user.

how I will define relations in models for this.

Any help would be greatly appreciated

Assuming your relationships are correctly created, I think this should work. Try it out and let me know how it goes:

$user_id = 1;
$user_data = Roles::whereHas('users', function (Builder $query) use ($user_id) {
        $query->where('id', $user_id);
    })->with(['permissions', 'resources'])->get();

It should return you a collection of Roles related to the specific user, with it's Permissions and Resources . For this to work, of course, Roles must have many Users .

This technique is documented here: https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence

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