Support the ongoing development of Laravel.io →
posted 9 years ago
Database
Last updated 2 years ago.
0

Did you define the relationship in you models? From the Laravel documentation:

Many-to-many relations are a more complicated relationship type. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin". Three database tables are needed for this relationship: users, roles, and role_user. The role_user table is derived from the alphabetical order of the related model names, and should have user_id and role_id columns.

We can define a many-to-many relation using the belongsToMany method:

class User extends Model {

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

}

Now, we can retrieve the roles through the User model:

$roles = User::find(1)->roles;

If you would like to use an unconventional table name for your pivot table, you may pass it as the second argument to the belongsToMany method:

return $this->belongsToMany('App\Role', 'user_roles');

You may also override the conventional associated keys:

return $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'foo_id');

Of course, you may also define the inverse of the relationship on the Role model:

class Role extends Model {

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

}
Last updated 9 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

SCC-Lee scc-lee Joined 22 Oct 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.