【发布时间】:2019-09-30 18:46:26
【问题描述】:
我正在尝试为我的每个模型创建动态数据库连接,以便可以使用 $model->setConnection('connection_name) 传递连接名称
我尝试了很多类似问题的答案,但没有任何效果
我创建了一个类,它创建一个新的数据库连接并将其添加到数据库配置中
<?php
namespace App;
use Illuminate\Support\Facades\Config;
class Clientdb
{
public $connection;
public function __construct($dbUser, $dbPassword, $dbName)
{
Config::set('database.connections.' . $dbUser, array(
'driver' => 'mysql',
'host' => '55.55.55.55',
'port' => '3306',
'database' => $dbName,
'username' => $dbUser,
'password' => $dbPassword,
'unix_socket' => '',
'charset' => 'utf8',
'collation' => 'utf8_general_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
\PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
));
$this->connection = $dbUser;
}
public function connection() {
return $this->connection;
}
}
在我的控制器中,我创建了一个新类的新实例以添加到数据库配置中,然后创建一个新的模型实例并将连接名称传递给我的模型 setConnection() 函数。
$this->clientdb = new Clientdb($dbUser, $dbPassword, $dbName);
$model = new \App\MyModel();
// dd($this->clientdb->connection);
$model->setConnection($this->clientdb->connection);
// dd($model);
$result = $model::where('id', $id)->first();
问题是它仍然尝试使用模型中设置的连接并且连接没有更新。如果我在模型中硬编码新的连接名称,它可以工作,但我需要使连接动态化,因为我不想继续手动添加到数据库配置中。
我错过了更新模型中的连接。
这是我的模型示例
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model
{
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'my_table';
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'mysql';
}
sdfsf
【问题讨论】:
标签: php laravel-5 eloquent database-connection