大佬教程收集整理的这篇文章主要介绍了Laravel 8 hasmanythrough (?) 与多个数据透视表,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
category_product 表(多对多):
ID
category_ID
product_ID
price_rules 表:
ID
title
discount_template_ID
start
end
category_price_rule 表(多对多):
ID
category_ID
price_rule_ID
如何获取产品的折扣模板(折扣模板应取自最新的 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();
它不会生成不必要的类别模型,看起来更干净并获取最新的(按价格规则)折扣模板。
以上是大佬教程为你收集整理的Laravel 8 hasmanythrough (?) 与多个数据透视表全部内容,希望文章能够帮你解决Laravel 8 hasmanythrough (?) 与多个数据透视表所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。