Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
619 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...