多对多 [英] Has many through many-to-many

查看:94
本文介绍了多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表格布局如下:

deals:
- id
- price

products:
- id
- name

deal_product:
- id
- deal_id
- product_id

metrics:
- id
- name

metric_product:
- id
- metric_id
- product_id
- value

productsmetrics与值的枢轴列具有多对多关系.

products and metrics have a many-to-many relationship with a pivot column of value.

dealsproducts也具有多对多关系.

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.

但是,如果您不想实现关系,那么我认为它可以满足您的需求:

But if you don't want to implement a Relation, I think that it can fulfill your needs :

在App \ Deal.php中,您可以组合@ thomas-van-der-veen的解决方案

In App\Deal.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.

这篇关于多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆