我使用 Laravel 的多态关系和变形图将不同的模型关联到单个表。但是,我遇到了一个问题,即只有变形贴图中的第一个模型有效,而其余模型都被忽略。
这是我设置变形贴图的方法:
Relation::morphMap([
'coupon' => Product::class,
'offer' => Product::class,
]);
public function scopefilter($query)
{
return $query->where(function ($query) {
// Include sliders with active morph relationships
$query->whereHasMorph('model','*', function ($query, $type) {
if (in_array($type,[ Blog::class, Coupon::class, Offer::class])) {
$query->active();
}
})->orWhereNull('model_type'); // Or include sliders without any morph
});
}
扩展模型Coupon、Offer等都继承自Product模型。
我面临的问题是,当我尝试使用 $slider->model 检索滑块的关联模型时,它仅返回产品实例,但如果它是优惠券、优惠则不返回实例。但是,当我更改变形贴图顺序时,只有贴图中的第一个起作用,其他的都被忽略。
我已验证数据库架构是否正确,并且所有模型均已正确自动加载。可能是什么原因导致此问题?我该如何解决?
如果您有
Coupon
和 Offer
的子类,请在变形贴图中使用它们。让它们都指向 Product
类将使 Laravel 实例化一个 Product
对象。
改变
Relation::morphMap([
'coupon' => Product::class,
'offer' => Product::class,
]);
到
Relation::morphMap([
'coupon' => Coupn::class,
'offer' => Offer::class,
]);