samedi 1 octobre 2016

Laravel model with multiple belongsToMany returning null

I have the following situation...

There are users which belong to groups and there are games which belong to groups.

I try to get all the user's groups but it returns NULL.

I have the relations set up as follows:

User model:

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

Group model:

public function games(){
    return $this->belongsToMany('App\Game');
}

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

group_user table

Schema::create('group_user', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->integer('group_id');
    $table->timestamps();
});

Now I try to get all the groups from a selected user

$user = User::find(1);

$userGroups = $user->groups;

So instead of $userGroups being all the groups of the user it's NULL (there is an entry in the group_user table containing IDs)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire