Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a has many through statement using laravel eloquent?

Say i have three tables users,users_groups and groups.How can i get the user's groups through the users_groups table?

class User extends Eloquent {
    protected $table = 'users';
}

class Groups extends Eloquent {
    protected $table = 'groups';
}

class Usergroups extends Eloquent {
    protected $table = 'users_groups';
}
like image 260
Roseann Solano Avatar asked Aug 24 '13 20:08

Roseann Solano


1 Answers

As per your request, I've put together a simple example for your specific use case:

The Tables:

Eloquent suggests creating 3 database tables in such a scenario: users, groups and group_user.

The Laravel documentation states that:

The group_user table's name is derived from the aplhabetical order of the related model names.

The group_user table should contain the columns user_id and group_id which will contain the primary keys of group and user entries. The group_user table is what's known as a pivot table.

This conforms to 3NF (if you're interested).

The Models:

The User model should contain the following code:

<?php 

class User extends Eloquent {

    //...Other code…

    public function groups()
    {
        return $this->belongsToMany('Group');
    }

} 

The Group model should contain the following code:

<?php

class Group extends Eloquent {

    //...Other code…

    public function users()
    {
        return $this->belongsToMany('User');
    }

    //...Other code…

}

You do not need a UserGroup model as found in your question.

Usage:

In order to retrieve all groups to which a particular user belongs you would do the following:

$user = User::find($user_id);
$user_groups = $user->groups();

Similarly in order to retrieve all users belonging to a particular group you would do the following:

$group = Group::find($group_id);
$group_users = $group->users();

In order to add/remove a user to a group would would do the following:

$user = User::find($user_id);
//Add a user
$user->groups()->attach($group_id);
//Detach a user
$user->groups()->detach($group_id);

Other:

You should read more in the Laravel docs about pivot tables here and about defining foreign keys (for your pivot table) in your migrations here.

I hope that helps!

like image 138
Hugo Firth Avatar answered Sep 28 '22 08:09

Hugo Firth