phplaraveleloquent-relationshipmultiple-databases

Get model relationship collection from another database in Laravel


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?


Solution

  • Based on the requirements of OP and checking out the description in docs, you might want to try HasManyThrough method:

    class User extends Model
    {
        /**
         * Get all of the orders for the user.
         */
        public function orders(): HasManyThrough
        {
            return $this->hasManyThrough(Orders::class, Customer::class);
        }
    }
    
    
    // String based syntax...
    return $user->through('customers')->has('orders');
     
    // Dynamic syntax...
    return $user->throughCustomers()->hasOrders();