skip to Main Content

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


  1. You might need to specify the connection inside the underlying IlluminateDatabaseQueryBuilder object when eager loading.

    $customers = Customer::query()
        ->with([
            'order' => function (HasMany $relation) {
                $eloquentBuilder = $relation->getQuery();
                $baseBuilder = $eloquentBuilder->getQuery();
                $baseBuilder->connection = DB::connection('mysql');
            },
        ])
        ->get();
    

    Applying this to a nested relationship:

    $user = User::query()
        ->with(['customers' => function (HasMany $customers_relation) {
            $customers_relation
                ->getQuery()
                ->getQuery()
                ->connection = DB::connection('second_db');
    
            $customers_relation->with(['orders' => function (HasMany $orders_relation) {
                $orders_relation
                    ->getQuery()
                    ->getQuery()
                    ->connection = DB::connection('mysql');
            }]);
        }])
        ...
        ->first();
    
    Login or Signup to reply.
  2. 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();
    

    The params customers and orders might be table names, not method names from OP’s users’ hasMany customer.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search