简体   繁体   中英

Connecting to two databases in Laravel 5

I can connect the databases in my project created by Laravel 5, but I use this code.

Is there any way to add User::all() before that ->select("select * from users"); ?

public function index(){
    $user = \DB::connection('nombrebd')->select("select * from users");
    $user2 = \DB::connection('nombrebd2')->select("select * from users");
    return $user+$user2;    
}

UPDATE

Sorry for my bad explanation , I need to receive all information about user in two differents databases.

If your intention is to use Eloquent as the base of your query to avoid writing actual SQL statements, you can do the following to get all users from each database:

$user = App::make('App\User')->setConnection('nombrebd')->get();
$user2 = App::make('App\User')->setConnection('nombrebd2')->get();

You can't use User::all() as you'd like, because that initialises a query builder instance and fetches the results all in one go, so there is no way to specify which connection it should use.

You could have two models, and in one of them you can specify an alternate connection:

protected $connection = 'mysql-alt';

Once you query both models, you can even merge them as such:

$users = $user_list_a->merge($user_list_b);

I use this approach when dealing with legacy databases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM