我有一个数据库表模型,基本上是一个表但在不同的数据库中, 如何在模型中设置与数据库的连接?
protected $connection = 'ls';
上面的代码不是我要找的,我需要传递主机、端口、用户名和密码。因为连接存储在数据库中而不是配置文件中。
我正在考虑 function __construct()
并调用 Model($data)::where()..etc
或者我的想法不对,谁能给我一个更好的主意。?
最佳答案
您可以通过维护以下方面从 Eloquent 模型连接
首先你可以在database.php
文件中定义多个连接
<?php
return array(
'default' => 'mysql',
'connections' => array(
# Our primary database connection
'mysql' => array(
'driver' => 'mysql',
'host' => 'host1',
'database' => 'database1',
'username' => 'user1',
'password' => 'pass1'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
# Our secondary database connection
'mysql2' => array(
'driver' => 'mysql',
'host' => 'host2',
'database' => 'database2',
'username' => 'user2',
'password' => 'pass2'
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
),
);
您的默认连接仍设置为 mysql
。这意味着,除非我们另外指定,否则应用程序将使用该 mysql
连接。
现在在您的模型中,您可以指定要使用的连接
<?php
class SomeModel extends Eloquent {
protected $connection = 'mysql2';
}
您还可以通过 setConnection 方法在运行时定义连接。
<?php
class SomeController extends BaseController {
public function someMethod()
{
$someModel = new SomeModel;
$someModel->setConnection('mysql2');
$something = $someModel->find(1);
return $something;
}
}
关于mysql - Laravel 动态模型数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33718375/