简体   繁体   中英

Laravel 4 - Chaining Many-to-Many relationships

I have these tables:

| users       |
|-------------|
| id          |
| name        |

| groups      |
|-------------|
| id          |
| name        |

| permissions |
|-------------|
| id          |
| name        |
| perm_key    | <- UNIQUE index

Then I have these many-to-many relationships:

groups -> groups_users <- users
groups -> groups_permissions <- permissions

So, any user may belong to several groups and each group may have a set of permissions.

Now I'm trying to get a Collection of DISTINCT User's with a given Permission key, or in another words, a Collection containing all the User's with access to the 'accessSpecialPlace' permission.

What I've got so far:

$key = 'accessSpecialPlace';
$permission = Permission::with('groups', 'groups.users')->where('permKey', '=', $key)->first();
$resultUsers = array();
foreach($permission->groups as $group) {
        foreach($group->users as $user) {
            $resultUsers[] = array(
                'id' => $user->id,
                'first_name' => $user->first_name
            );
        }
    }
return Response::json($resultUsers, 200, array(), JSON_PRETTY_PRINT);

This is working flawlessly so far, except that it's not yet a Collection (I've just added them to an array) and it's not yet distinct (because if a user belongs to 2 groups which have access to that permission, they will appear twice).

PS: I didn't expect to get the eager loading part working so easily in my first try! I love this framework!

Create a collection instead of an array, and use put to store the users keyed by their id:

$permission = Permission::with('groups.users')->where('permKey', $key)->first();

$users = new Illuminate\Support\Collection;

foreach ($permission->groups as $group)
{
    foreach ($group->users as $user)
    {
        $users->put($user->id, $user);
    }
}

If you want the collection to contain arrays instead of models, pass an array as the 2nd argument to put .


PS Using a hasManyThrough relationship here would simplify things.

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