3

I have 3 databases defined in my app (legacy not my design!) and I want to use DB Select to run a raw SQL but not from the primary DB.

What is the syntax for telling

 DB::select('SELECT....

to use a particular predefined connection?

2
  • You can set up multiple database in the config file and use this DB::connection('foo')->select(...); Commented Nov 3, 2016 at 10:12
  • I have done that and named one of the connections "common" and added "protected $connection = 'common';" at the top of the model but it seems to always want to select from the default DB. Commented Nov 3, 2016 at 10:18

1 Answer 1

6

The reason why the $connection declaration seems to be ignored is simple: with the Query Builder (DB class) you are actually not using the Eloquent ORM. If you want to use the Query Builder, you have to manually declare the connection if different from default, like this...

DB::connection('connection-name')

Remember that the Eloquent models are extensions of the Query Builder. For taking advance of the Eloquent model (and in your case of the $connection protected property) import the Eloquent Model with a use statement

use App\YourModel;

and build the query with the same methods that you'd use with the query builder.

Useful links to Laravel docs:

Eloquent (check the "Database connection" section) / Database - Multiple database connections

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.