Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsToMany relationship defining local key on both tables

So the belongsToMany relationship is a many-to-many relationship so a pivot table is required

Example we have a users table and a roles table and a user_roles pivot table.

The pivot table has two columns, user_id, foo_id... foo_id referring to the id in roles table.

So to do this we write the following in the user eloquent model:

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

Now this looks for an id field in users table and joins it with the user_id field in the user_roles table.

Issue is I want to specify a different field, other than id to join on in the users table. For example I have bar_id in the users table that I want to use as the local key to join with user_id

From laravel's documentation, it is not clear on how to do this. In other relationships like hasMany and belongsTo we can specify local key and foriegn key but not in here for some reason.

I want the local key on the users table to be bar_id instead of just id.

How can I do this?

like image 964
user1952811 Avatar asked Jun 24 '14 16:06

user1952811


1 Answers

Update: as of Laravel 5.5 onwards it is possible with generic relation method, as mentioned by @cyberfly below:

public function categories()
{
    return $this->belongsToMany(
         Category::class,
         'service_categories',
         'service_id',
         'category_id', 
         'uuid',  // new in 5.5
         'uuid'   // new in 5.5
    );
}

for reference, previous method:

I assume id is the primary key on your User model, so there is no way to do this with Eloquent methods, because belongsToMany uses $model->getKey() to get that key.

So you need to create custom relation extending belongsToMany that will do what you need.

A quick guess you could try: (not tested, but won't work with eager loading for sure)

// User model
protected function setPrimaryKey($key)
{
  $this->primaryKey = $key;
}

public function roles()
{
  $this->setPrimaryKey('desiredUserColumn');

  $relation = $this->belongsToMany('Role', 'user_roles', 'user_id', 'foo_id');

  $this->setPrimaryKey('id');

  return $relation;
}
like image 115
Jarek Tkaczyk Avatar answered Oct 04 '22 23:10

Jarek Tkaczyk