简体   繁体   中英

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)

你有尝试过吗?

return $this->belongsToMany('App\User', 'group_user','user_id', 'group_id');

As suggested by: Paul Spiegel

$user->groups()->get()

Worked! Thank you :)

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