繁体   English   中英

Laravel 8 hasmanythrough (?) 与多个 pivot 表

[英]Laravel 8 hasmanythrough (?) with multiple pivot tables

category_product 表(多对多):

id
category_id
product_id

价格规则表:

id
title
discount_template_id
start
end

category_price_rule 表(多对多):

id
category_id
price_rule_id

如何获取产品的折扣模板(折扣模板应取自 latest by id 价格规则)? 目前我有这个方法:

private function price_rule_dt() {
    $dt = NULL;
    foreach($this->categories as $category) {
        if($category->price_rules->count() > 0) {
            $dt = $category->price_rules->first->discount_template;
        } 
    }
    return $dt;
}

它有效,但没有获得最新的折扣模板。 此外,调试栏显示重复生成的模型,并且每次我尝试加载产品时都需要混乱的急切加载:

Product::with('categories.price_rules.discount_template')->get();

我相信它应该是这样的:

Product::with('price_rule_dt')->get();

有没有比我现在更好的解决方法? 谢谢。

所以我想出了一个这样的解决方案:

public function category_price_rules()
{
    return $this->hasManyThrough(
        CategoryPriceRule::class,
        CategoryProduct::class,
        'product_id', 
        'category_id', 
        'id', 
        'category_id' 
    )->orderBy('id', 'DESC');
}
...
Product::with('category_price_rules.price_rule.discount_template')->get();

它不会生成不必要的类别模型,看起来更干净并获得最新的(按价格规则)折扣模板。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM