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

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -