laravel更改数据库连接运行时间 [英] laravel Change Database connection run time

查看:186
本文介绍了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.

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

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';为每个雄辩的模型指定一个连接,也可以为在运行时创建/查询的每个模型实例指定一个连接

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更改数据库连接运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆