Application 2017-10-01

Excluding Table Names from Laravel's Many-to-Many Relations

Configure Laravel many-to-many relationships with custom pivot table names in Eloquent relationships.

Read in: ja
Excluding Table Names from Laravel's Many-to-Many Relations

When designing many-to-many relationships, I thought I was following the documentation, but I had a slight misunderstanding.

Here are three tables, right?

The tables in this case:

For normal tables:

You would typically set up the relationship according to the default conventions, but when using slightly unconventional names, there are some things to be cautious about.

Let's take a look at the documentation

Laravel 5.1 Eloquent: Relationships

Ah, so I just need to provide a second argument!

public function eventTags()
{
  // The second argument is the Pivot table!
  return $this->belongstoMany('App\Modles\EventTag', 'event_tag_event')->withTimestamps();
}
public function events()
{
  return $this->belongsToMany('App\Models\Events');
}

When I launched tinker to check...

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship

I got an error. ヽ(´ー`)ノ

The second argument is the Pivot table name!

Could it be that I need to specify the Pivot table name?

SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias on relationship

public function eventTags()
{
  // The second argument is the Pivot table!
  return $this->belongstoMany('App\Modles\EventTag', 'event_tag_event')->withTimestamps();
}
public function events()
{
  return $this->belongsToMany('App\Models\Events');
}

I didn't get an error this time. ヽ(´ー`)ノ

Thoughts

Recently, I've been more interested in the front end than the back end, and I can't sleep at night. ヽ(´ー`)ノ

Tags: Laravel
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles