[英]How to link attribute in Yii 2 to another model's field?
我通過 hasOne 關系擁有 Products 模型和 ProductProperties:
class Product extends ActiveRecord
{
...
public function getProductProperties()
{
return $this->hasOne(ProductProperties::class, ['product_id' => 'id']);
}
...
}
我在 Products 中有價格屬性,我想刪除它(包括數據庫中的列)並將其鏈接到 ProductProperties 模型的價格屬性。 有可能嗎?我該怎么做? 首先,我嘗試像這樣覆蓋屬性方法:
public function fields()
{
return [
'price' => function () {
return ProductProperties::find(['product_id' => $this->id])->price;
}
]
...
但我不確定是否可以使用箭頭方法分配值。 此外,fields() 方法在返回任何內容之前使用$this->price
:
public function fields()
{
if ($this->price){*some manipulations with price*}
...
return [
'price',
..*other fields*
];
}
問題是如何從模型中刪除價格並使用另一個模型的價格屬性而不會有太多痛苦?
如果你只想顯示價格,你可以這樣做
class Product extends ActiveRecord
{
...
public function getProductProperties()
{
return $this->hasOne(ProductProperties::class, ['product_id' => 'id']);
}
public function getPrice() {
return $this->productProperties->price;
}
...
}
並使用它
$product = Product::findOne(1);
echo $product->price; // this is a shortcut
echo $product->productProperties->price; // same as this which is the complete route
要保存數據,您應該首先確定如何處理用戶數據收集,因為您有不同的模型並且每個模型都有自己的驗證。
但是,如果您想將價格保存為產品屬性(我不推薦),您可以執行以下操作
class Product extends ActiveRecord
{
public $price;
public function rules () {
return [
[['price'], 'integer'] // for massive assignment
];
}
public function afterFind()
{
parent::afterFind();
$this->price = $this->productProperties->price;
}
public function getProductProperties()
{
return $this->hasOne(ProductProperties::class, ['product_id' => 'id']);
}
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
if (array_key_exists('price', $changedAttributes)) {
// You should make sure that $this->productProperties exists.
$this->productProperties->price = $this->price;
$this->productProperties->save();
}
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.