2016-10-09 2 views
1

私は2つのモデル、すなわちProduct,ProductPriceで小さなシステムを作ろうとしています。ここで追加クエリなしでLaravelの子どもから親を取得

は、製品のモデルである:

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()を使用する必要があることを想像してみましょうモデル。この例では、私のgetTaxIncludedPriceAttribute()メソッドがproduct属性を見つける新しい要求をするため、無限ループの例外を取得します。私は親を介してにアクセスする場合

は、だから私はProductPriceモデルでProduct親にアクセスすることができ、余分なクエリだから、

答えて

0

をせずに、私はのわからない、手作りの溶液を用いて問題を解決しました私はそれが動作するように動作します。

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; 
    } 
} 

見ての通り、私は

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); 
    } 
} 
...それを問い合わせる再ずに関係の親を定義する $relation->loadProduct($this);を実行します
関連する問題