php - Force the write database connection on Laravel relationships -


i'm using separate read , write connections in laravel app:

'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,         ], 

normally, if i'd force write connection used, i'd write:

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

this works fine, directly on model. if have case need use write connection throughout 1 specific method uses relations, this:

$user = user::find(123);  $user->universities()->attach(array(34, 56, 2)); $user->universities()->dettach(array(4, 78));  $primary = $user->universities()->where('primary', 1)->first();  // , on... 

i'd all relation-based operations (regardless whether are, in fact, read or write ones) done on write connection.

how do in laravel?

what tried:

(1) using onwriteconnection() method on relations - doesn't work due fact method static , directly connected eloquent model object.

(2) using setconnection() method:

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

which throws error driver index not specified connection - makes sense , proves it's not right way it.

you directly use usewritepdo() method of query builder, onwriteconnection() calls behind scene:

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

Comments

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -