Laravel 5如何在控制器内更改模型数据库连接 [英] Laravel 5 How to change a model database connection within controller

查看:102
本文介绍了Laravel 5如何在控制器内更改模型数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序应连接到内部和两个外部商业SQL数据库.

My app should connect to an internal and two external commercial SQL databases.

因此,我有几种模型可以连接到外部MS-SQL数据库.

So, I have several models with a connection to an external an MS-SQL database.

模型看起来像这样:

class version_Jato extends Model
{
    //
    protected $connection = 'sqlJato';
    protected $table = 'version';
....
}

直到现在,一切正常,应用程序可以使用两个数据库.

Until now, everything OK, app works with two databases.

我想更改控制器内的$ connection变量,让我们说

I want to change $connection variable within the controller to let's say

version_Jato-> $connection = 'sqlJato2'.

这可能吗?

因为我有两个结构相同的SQL数据库,只是它们之间的数据不同,所以我不想将所有模型和控制器中的代码加倍.

Because I have two SQL databases identical as structure only the data is different between them and I don't want to double all the models and the code in the controllers.

非常感谢您的关注!

推荐答案

您可以使用on()静态方法切换连接:

You can switch the connection using the on() static method:

YourModel::on('connection_name')->get();

源代码

这篇关于Laravel 5如何在控制器内更改模型数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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