我正在尝试用两个模型制作一个小系统:Product
, ProductPrice
。
产品型号:
class Product extends Model
{
protected $with = ['prices'];
public $tax_rate = 0.2;
public function prices ()
{
return $this->hasMany(ProductPrice::class);
}
}
我把tax_rate
常数放在这里更清楚,但在现实世界中,它是由另一个关系处理的。
这里最重要的是tax_rate
是Product
模型的一个属性
ProductPrice
模型:
class ProductPrice extends Model
{
protected $appends = ['tax_included_price'];
public function getTaxIncludedPriceAttribute()
{
return (1 + $this->product->tax_rate) * $this->price;
}
public function product ()
{
return $this->belongsTo(Product::class);
}
}
现在让我们想象我需要在一些模型上使用$product->toArray()
。在这个例子中,我将得到一个无限循环的Exception,因为我的getTaxIncludedPriceAttribute()
方法发出了一个新的请求来查找product
属性。
所以我可以访问ProductPrice
模型中的Product
父级,如果我通过父级访问它,而无需进行额外的查询
所以,我用手工解决了这个问题,不确定实现,但它像我想要的那样工作。
class Product extends Model
{
protected $with = ['pricesRelation'];
protected $appends = ['prices'];
public $tax_rate = 0.2;
public function pricesRelation ()
{
return $this->hasMany(ProductPrice::class);
}
public function getPricesAttribute ()
{
$collection = new Collection();
foreach($this->pricesRelation as $relation) {
$relation->loadProduct($this);
$collection->add($relation);
}
return $relation;
}
}
如您所见,我运行$relation->loadProduct($this);
来定义父关系而不重新查询它…
class ProductPrice extends Model
{
protected $appends = ['tax_included_price'];
protected $loaded_product;
public function getTaxIncludedPriceAttribute()
{
$tax_rate = is_null($loaded_product) ? $this->product->tax_rate : $this->loaded_product->tax_rate;
return (1 + $tax_rate) * $this->price;
}
public function loadProduct (Product $product)
{
$this->loaded_product = $product;
}
public function product ()
{
return $this->belongsTo(Product::class);
}
}