Forcing record database connection to Laravel relationship

I am using separate connections read

and write

in my Laravel application:

'mysql' => [
            'write' => ['host' => env('DB_HOST_WRITE', 'localhost'),],
            'read'  => ['host' => env('DB_HOST_READ', 'localhost'),],
            'driver' => 'mysql',
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'very'),
            'username' => env('DB_USERNAME', 'secret'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => false,
            'engine' => null,
        ],

      

Usually, if I want to force the connection write

, I would write:

$user = User::onWriteConnection()->where('email', 'test@example.com')->first();

      

This works great, right on the model. But what if I have a case where I need to use a connection write

over one specific method that uses relationships, for example:

$user = User::find(123);

$user->universities()->attach(array(34, 56, 2));
$user->universities()->dettach(array(4, 78));

$primary = $user->universities()->where('primary', 1)->first();

// and so on...

      

I would like all these relationship based operations (regardless of whether they are, in fact, read or written) to be connected write

.

How do I do this in Laravel?

What I have tried:

(1) Using the method onWriteConnection()

by relationship - does not work due to the fact that method is static and is directly related to the Elementary Model object.

(2) Using the method setConnection()

:

$user = User::find(123);
$user->setConnection('mysql.write');

      

which throws an error indicating that no index driver

was specified for the join, which makes sense and proves that this is not the correct way to do it.

+3


source to share


1 answer


You can directly use the useWritePdo()

query builder method that onWriteConnection()

calls behind the scenes:



$primary = $user->universities()->useWritePdo()->where('primary', 1)->first();

      

+5


source







All Articles