This this the structure that I currently use
Model User :
class User extends Authenticatable implements MustVerifyEmail
public function groups()
{
return $this->belongsToMany('App\Group')
->withTimestamps();
}
Model Group :
class Group extends Model
public function users() {
return $this->belongsToMany('App\User')
->withTimestamps();
}
Pivot table :
Schema::create('group_user', function (Blueprint $table) {
$table->integer('group_id');
$table->integer('user_id');
$table->integer('role_id')->nullable();
$table->timestamps();
});
I would like to get all the users who are in same groups of the current user and don't return duplicate users (a user can be in multiple groups). The ideal functions would be :
$user->contacts()
// Return an object with (unique) contacts of all current user groups
AND
$user->groupContacts($group)
// Witch is the same as $group->users
// Return an object with all the users of the current group
There is the not functional function i'm working on (Model User.php) :
public function contacts()
{
$groups = $this->groups;
$contacts = new \stdClass();
foreach ($groups as $key => $group) :
$contacts->$key = $group->users;
endforeach;
return $contacts;
}
I'm really not an expert with table structures so if there is a better way to do this, i'm only at the beginning of this personnal project so nothing is written in stone.
Optional stuffs :
- Exclude current user from the list
- With roles from pivot table
- With softdelete
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire