Different db connection for models using hasManyThrough relationship in laravel 5.1

I am trying to use the hasManyThrough relation in laravel 5.1, but the sql query does not use the corresponding prefix defined in each connection for each model used. I have 3 models, 2 of which use the same connection, and one of them uses the other. The only difference between the connections is the prefix, which is the database.

  • Model A has a connection A that uses the prefix A _
  • Model B has a connection B that uses the prefix B _
  • Model C has a connection B that uses the prefix B _

Attitude:

Inside model B:

public function relationshipWithA() { return $this->hasManyThrough(A::class, C::class, 'Cid', 'Aid'); } 

The final query logic is correct, but instead of using the B_ prefix for joined tables, the A_ prefix is ​​used for all tables in the query.

Is this a laravel bug / restriction? Is there a solution for this or will I have to do a manual connection to achieve what I want?

+7
php mysql eloquent laravel-5 query-builder
source share
1 answer

Other types of relationships work with multiple database connections:

 public function foos() { return $this->belongsToMany(Foo::class, 'other_db.foos'); } 

But hasManyThrough does not have the $table parameter in its signature, so the same solution is not applicable.

but

You can make the wrong workaround as follows:

 public function bars() { return $this->belongsToMany(Bar::class, 'other_db.bars'); } public function foos() { $barIds = $this->bars->pluck('id'); return Foo::whereIn('bar_id', $barIds); } 

It does not offer exactly the same functionality (since this is a different type of return), but fulfills the purpose for simpler things.

If you want, you can also reproduce another syntax by doing something like this:

 protected $appends = [ 'foos', ]; /** * @return Foo[] */ public function getFoosAttribute() { return $this->foos()->get(); } 

That way, you can still use it in your code, as in most cases, with regular relationships (which means you can use $this->foos instead of $this->foos()->get() )

+1
source share

All Articles