【发布时间】:2015-05-18 02:40:23
【问题描述】:
这是一个来自
的后续问题Forcing Eloquent models to re resolve database connection
有多个数据库连接:
return [
'default' => 'mysql-key1',
'connections' => [
'mysql-key1' => [
'driver' => 'mysql',
'database' => 'key1_dbname,
// etc
],
'mysql-key2' => [
'driver' => 'mysql',
'database' => 'key2_dbname',
// etc
]
]
];
我有一个产品存储库,它使用模型 setConnection 来更改连接属性:
public function setConnection($name) {
// assumes $this->product is your Product model
$this->product->setConnection($name);
}
但是,我发现它只适用于查询方法,而不适用于 Model::create ::
$productRepo = new ProductRepository();
foreach ($array as $key => $value) {
$productRepo->setConnection($key . '_' . $database);
// this works
$products = $productRepo->all();
// this doesn't work and will use the old connection
$product = $productRepo->create($data);
}
似乎 ::create 方法在创建实例后无法解析连接。有人知道解决办法吗?
【问题讨论】:
标签: php database laravel eloquent