laravel 更改数据库连接运行时

时间:2022-10-18
本文介绍了laravel 更改数据库连接运行时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要在运行时更改 Laravel 5 数据库连接.

I need to change laravel 5 database connection in run time.

你有什么想法吗?

请分享给我.

谢谢.

推荐答案

更新:这个答案来自 2015 年!我已经很多年没有使用 Laravel 了,我也没有掌握最新的最佳实践.这个答案不断得到支持,所以我认为它有效,但请谨慎行事.

Update: This answer is from 2015! I haven't used Laravel in years and I am not up to date with the latest best practices. This answer keeps getting upvoted so I suppose it works but please proceed with caution.

好吧,我对此的直接回答是:不要.您可以通过更改数据模型和使用一些更高级的关系来完成任务.不知道你想做什么很难说,但在我看来,这通常是个坏主意,特别是如果你打算使用 eloquent 模型等等

Well, my immediate answer to this is: don't. Chances are that you can accomplish your task by changing your data model and working with some more advanced relationships. It's hard to tell without knowing what you want to do but it seems to me like a bad idea in general, specially if you're planning on using eloquent models and so on

也就是说,在某些情况下,您确实需要更改另一个数据库中的数据或执行一些原始查询,您可以使用 DB::connection() 方法.类似的东西:

That said, in some scenario where you really need to alter data in another database or execute some raw query you can use the DB::connection() method. Something like:

$data = DB::connection('another_connection')->select(...);

您可以在 database.php 文件中指定 another_connection 变量.像这样:

You can specify that another_connection variable at your database.php file. Like this:

<?php
return array(

'default' => 'mysql',

'connections' => array(

    # Your regular connection
    'mysql' => array(
        'driver'    => 'mysql',
        'host'      => 'localhost',
        'database'  => 'database',
        'username'  => 'user',
        'password'  => 'password'
        'charset'   => 'utf8',

    ),

    # Your new connection
    'another_connection' => array(
        'driver'    => 'mysql',
        'host'      => 'another_host',
        'database'  => 'another_db',
        'username'  => 'user1',
        'password'  => 'password1'
        'charset'   => 'utf8',
    ),
),
);

您甚至可以使用 protected $connection = 'another_connection'; 为每个 eloquent 模型指定一个连接 也可以为每个在运行时创建/查询的模型实例指定一个连接

You can even specify a connection for each eloquent model using protected $connection = 'another_connection'; also you can specify a connection for each model instance created/queried at run time

$user = new User;
$user->setConnection('another_connection');
$user1 = $user->find(1);

但话说回来,我个人认为这不是一个好主意,而且在我看来,随着应用程序复杂性的增加,一切都会变得混乱并很快崩溃.

But then again, I personally don't think this is a good idea and it seems to me that everything can get messy and fall apart very quickly as your application grows in complexity.

这篇关于laravel 更改数据库连接运行时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:为什么在 Laravel 5.x 中不推荐使用 Form 和 HTML 助手? 下一条:Laravel 5 Form Request 数据预操作

相关文章

最新文章