One minute
Laravel Cross DB Has Many Through Relationship
Recently, I found a bug in Laravel 9 where I needed to establish a hasManyThrough relationship on a model with another model that was in a different database (but on the same server). While debugging, I discovered that Laravel was not including the database name before the table name in the MySQL joins, which caused the standard “table not found” error.
class FooBar extends Model
{
public function getTable(): string
{
return $this->getConnection()->getDatabaseName() . '.' . parent::getTable();
}
}
As long as both of the models have their $table
and $connection
properties set, you can use the standard hasManyThrough syntax.
class BazQux extends Model
{
public function deployments()
{
return $this->hasManyThrough(FooBar::class, QuuxCorge::class);
}
}
I’m not sure if this is fixed in Laravel 10, but as of version 9.52.7, this is the only way I could make it work.