问题描述
我有以下表格布局:
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
与值的枢轴列具有多对多关系.
products
and metrics
have a many-to-many relationship with a pivot column of value.
deals
和 products
也有多对多的关系.
deals
and products
also have a many-to-many relationship.
我可以使用 $product->metrics
获取产品的指标,但我希望能够获取与交易相关的所有产品的所有指标,因此我可以执行以下操作: $deal->metrics
.
I can get metrics for a product with $product->metrics
, but I want to be able to get all metrics for all products related to a deal, so I could do something like this: $deal->metrics
.
我的 Deal
模型中目前有以下内容:
I currently have the following in my 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 this doesn't return a relationship, so I cannot eager load it or get related models from it.
它需要采用关系格式,因为它们需要为我的用例预先加载.
It needs to be in relationship format, because they need to be eager loaded for my use case.
感谢您的帮助!
推荐答案
如果你想有一个自定义的关系,你可以创建你自己的扩展到 Relation 抽象类.例如:BelongsToManyThought
.
If you want to have a custom relation, you can create your own extends to Relation abstract class. For example: BelongsToManyThought
.
但是如果你不想实现一个 Relation,我认为它可以满足你的需求:
But if you don't want to implement a Relation, I think that it can fulfill your needs :
在AppDeal.php中,可以结合@thomas-van-der-veen的解决方案
In AppDeal.php, you can combine the 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);
}
// you can access to $deal->metrics and 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 to this post to see how you can simply use nested relations.
这个解决方案可以用来查询与方法的关系并访问度量属性.
This solution can do the trick for querying relation with method and access to metrics attribute.
这篇关于有很多通过多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!