問題描述
這是來自
強制 Eloquent 模型重新解析數據庫連接
有多個數據庫連接:
return [
'default' => 'mysql-key1',
'connections' => [
'mysql-key1' => [
'driver' => 'mysql',
'database' => 'key1_dbname,
// etc
],
'mysql-key2' => [
'driver' => 'mysql',
'database' => 'key2_dbname',
// etc
]
]
];
我有一個使用模型 setConnection 更改連接屬性的產品存儲庫:
I have a product repository which uses the Model setConnection to change the connection attribute :
public function setConnection($name) {
// assumes $this->product is your Product model
$this->product->setConnection($name);
}
然而,我發現它只適用于查詢方法,而不適用于 Model::create ::
However, i found out that it only worked on query methods and not methods like 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 方法就不會解析連接.有人知道修復嗎?
Seems that the ::create method does not resolve the connection once the instance has been created. Anyone knows a fix?
推薦答案
問題是 setConnection()
作用于一個類的實例,但是 create()
> 方法是類本身的靜態方法.在您的存儲庫中,$this->product
是 Product 類的一個實例.在執行查詢之前在此實例上使用 setConnection()
會正常工作,但是如果您想在靜態方法上使用單獨的連接(例如 create()
).
The problem is that setConnection()
works on an instance of a class, but the create()
method is a static method on the class itself. In your repository, $this->product
is an instance of the Product class. Using setConnection()
on this instance before doing queries will work fine, but you'll need to do a little more manual work if you want to use separate connections on the static methods (such as create()
).
create()
方法所做的就是用給定的屬性實例化一個新實例,然后調用 save()
.因此,無需在 Product 模型上調用 create()
,您只需手動執行此操作:
All the create()
method does is instantiate a new instance with the given attributes and then call save()
. So, instead of calling create()
on the Product model, you'll just need to do this manually:
class ProductRepository {
public function create(array $attributes, $connection = null) {
$product = $this->product->newInstance($attributes);
$product->setConnection($connection ?: $this->product->getConnectionName());
$product->save();
return $product;
}
}
您還可以覆蓋 Product 模型上的靜態 create()
方法以接受連接.
You could also override the static create()
method on the Product model to accept a connection, as well.
class Product extends Model {
public static function create(array $attributes, $connection = null) {
$model = new static($attributes);
$model->setConnection($connection ?: $this->connection);
$model->save();
return $model;
}
}
class ProductRepository {
public function create(array $attributes, $connection = null) {
$connection = $connection ?: $this->product->getConnectionName()
return $this->product->create($attributes, $connection);
}
}
這篇關于Laravel Eloquent ORM 中的多租戶的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!