1

Im wondering is it possible to change database name within the same connection?

The reason is that Im working on a report which needs to loop through all of the databases (more than 100) within the same connection (host, user, pass).

Currently I just manually add the database name before each table name in query. Like:

"SELECT * FROM `database_a`.`users` WHERE ...";

I made some searches on Google with "change database name" or "switch database..." but most of them are about creating different connections array in config/database.php but thats not my case (with more than 100 databases)

Thanks

1
  • What kind of database? Commented Jun 23, 2017 at 20:44

2 Answers 2

4

What about defining database in table selection ?

class Book extends Model {

    protected $table = 'database1.books'

}

class Book2 extends Model {

    protected $table = 'database2.books'

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

1 Comment

Im using raw query :((
1

Since you are only changing the database name, create an array with all your databases names. Then using query builder you can do in a loop

DB::table($databasesArray[0].'.table_name')->where(...)

I think this would put you in the right track. E.g:

$databases = ['db1','db2'];

foreach($databases as $db) {
    $users [] = DB::table($db.'.users')->where('status', 'active')->get();
}
// $users = all users from all Databases

1 Comment

Yeah thats what im doing, however I dont think thats good approach because I have to manually build the database name array. Thanks anw

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.