简体   繁体   English

连接到Laravel 5中的两个数据库

[英]Connecting to two databases in Laravel 5

I can connect the databases in my project created by Laravel 5, but I use this code. 我可以在Laravel 5创建的项目中连接数据库,但是我使用此代码。

Is there any way to add User::all() before that ->select("select * from users"); 在此之前,有什么方法可以添加User::all() ->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: 如果要使用Eloquent作为查询的基础以避免编写实际的SQL语句,则可以执行以下操作从每个数据库中获取所有用户:

$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. 您无法随意使用User::all() ,因为这会初始化查询构建器实例并一次性获取所有结果,因此无法指定应使用的连接。

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. 在处理旧数据库时,我使用这种方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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