Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

RonnieVisser's avatar

belongsToMany with table definition produces wrong query.

  • Laravel Version: 9.21.4
  • PHP Version: 8.1.
  • Database Driver & Version: pgsql 13

Description:

I'm currently migrating our application to use postgres instead of mysql. to make full use of the schema functionality we have to be more specific when using belongsToMany relationship to also include the table with schema prefix since we have a referees table in 2 schema and search_path might turn in to unwanted outcomes.

Please find an example of a query produced with belongsToMany with table definition:

public function referees(): BelongsToMany
{
	return $this->belongsToMany(Referee::class, 'sports.referees'); // 'referees' only produces the same query.
}
select "sports"."referees".*, "referees"."fixture_id" as "pivot_fixture_id", "referees"."referee_id" as "pivot_referee_id" 
from "sports"."referees" 
inner join "referees" on "sports"."referees"."id" = "referees"."referee_id" where "referees"."fixture_id" in (*, *, *))

As you can see it genenrated and extra join on to the same table which is rejected by postgresql. ERROR: table name "referees" specified more than once.

When removing the table definition or when using a custom pivot this error is not produced.

public function referees(): BelongsToMany
{
	return $this->belongsToMany(Referee::class);
}

or

public function referees(): BelongsToMany
{
	return $this->belongsToMany(Referee::class)->using(FixtureReferee::class);
}

Note that the FixtureReferee pivot has a

protected $table = 'sports.referees';
0 likes
1 reply

Please or to participate in this conversation.