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';
}
As per your request, I've put together a simple example for your specific use case:
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 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.
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);
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With