Search code examples
phplaraveleloquentloadingeager

Laravel Eloquent eager loading on a different connection


I am trying to use Laravel Eloquent ORM to do a simple one to one relationship on two different connections.

Let say I do :

MyModel::on('secondary_connection')->get()

That is working fine.

When I do :

MyModel::on('secondary_connection')->with('AnotherModel')->get();

I am getting an error because eloquent is doing the AnotherModel SELECT statement on the default connection (instead of "secondary_connection").

I can't find a way to work this around.

My models are well defined since I can join them in my default connection.

Thoughts ?


Solution

  • Well, as I've been suggested by many users, it seems that there's no way to do this on the fly. My understanding of this is that Eloquent is incomplete when comes to manage multi-connection.

    There's 2 way to work this around I could figure.

    First, specify the connection in the model :

    class MyModel {
        $protected connection = 'secondary_connection';
    }
    

    That is obviously a bad workaround since this model is only usable in one connection... but still works.

    Then, as Jarek Tkaczyk suggested, it is possible to switch de default connection with the new one. But instead of doing it in the config file, it is possible to swap the PDO oject.

        $default = DB::getPdo(); // Default conn
        $secondary = DB::connection('secondary_connection')->getPdo();
        DB::setPdo($secondary);
        $result = MyModel::with('AnotherModel')->get();
        DB::setPdo($default);
    

    That is a workaround that works and can be a clean solution. Next step is to put that switching mechanism in a nice Laravel way.