laravel - Has many through many-to-many -
i have following table layout:
deals: - id - price products: - id - name deal_product: - id - deal_id - product_id metrics: - id - name metric_product: - id - metric_id - product_id - value
products
, metrics
have many-to-many relationship pivot column of value.
deals
, products
have many-to-many relationship.
i can metrics product $product->metrics
, want able metrics products related deal, this: $deal->metrics
.
i have following in deal
model:
public function metrics() { $products = $this->products()->pluck('products.id')->all(); return metric::wherehas('products', function (builder $query) use ($products) { $query->wherein('products.id', $products); }); }
but doesn't return relationship, cannot eager load or related models it.
it needs in relationship format, because need eager loaded use case.
thanks help!
if want have custom relation, can create own extends relation abstract class. example: belongstomanythought
.
but if don't want implement relation, think can fulfill needs :
in app\deal.php, can combine solution of @thomas-van-der-veen
public function metrics() { return metric ::join('metric_product', 'metric.id', '=', 'metric_product.metric_id') ->join('products', 'metric_product.product_id', '=', 'products.id') ->join('deal_product', 'products.id', '=', 'deal_product.product_id') ->join('deals', 'deal_product.deal_id', '=', 'deal.id') ->where('deal.id', $this->id); } // can access $deal->metrics , use eager loading public function getmetricsattribute() { if (!$this->relationloaded('products') || !$this->products->first()->relationloaded('metrics')) { $this->load('products.metrics'); } return collect($this->products->lists('metrics'))->collapse()->unique(); }
you can refer post see how can use nested relations.
this solution can trick querying relation method , access metrics attribute.
Comments
Post a Comment