Laravel 5如何在控制器内更改模型数据库连接 [英] Laravel 5 How to change a model database connection within controller
问题描述
我的应用程序应连接到内部和两个外部商业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屋!