且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多对多

更新时间:2022-12-30 21:35:16

如果您要具有自定义关系,则可以创建自己的对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.