I have set the connection to two databases properly. I also have created eloquent table models and I can query a single table relationship from another database easily e.g.
$user->customer
User model
class User extends Model
{
protected $connection = 'mysql';
protected $table = 'users';
public function customer()
{
return $this->hasMany(Customer::class, 'user_id', 'id');
}
}
Customer model
class Customer extends Model
{
protected $connection = 'second_db';
protected $table = 'customers';
public function order()
{
return $this->hasMany(Order::class, 'customer_id', 'id');
}
}
I can get the orders data in the second database using this simple query
$customer->order
But it give an empty result when querying from the first database using
$user->customer->order
or
$user->customer()->order
How to get the relationship data in the second dB by querying from the first dB?
2
Answers
You might need to specify the connection inside the underlying
IlluminateDatabaseQueryBuilder
object when eager loading.Applying this to a nested relationship:
Based on the requirements of OP and checking out the description in docs, you might want to try
HasManyThrough
method:The params
customers
andorders
might be table names, not method names from OP’s users’hasMany customer
.