1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Eloquent Builderを使ってDB接続先を動的に切り替える方法

Posted at

Eloquent Builderを使ってDB接続先を動的に切り替える方法

$c = new Customer();
$c->setConnection('db_replica')->newModelQuery()->where('id', 1)->get();
// もしくは
$c->setConnection('db_replica')->where('id', 1)->get();

// これはNG (connection情報が失われて、default に繋がれてしまう)
$c->setConnection('db_replica')->query()->where('id', 1)->get();

Illuminate\Database\Query\Builder はドキュメントにあってその通りだけど、モデル使う場合が情報量少なくてちょっとハマったので共有でした

\DB::connection('db_replica')->table('customers')->where('id', 1)->get();
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?