【发布时间】:2020-11-09 05:19:54
【问题描述】:
Laravel 版本:7.0
reviews 表(模型 - 审查)具有 id、product_type、product_id、rating 列。
product_type 可以是service、plugin、module,每个值都有自己的模型App\Service、App\Plugin、App\Module。我可以将model names 直接放入product_type,但我更喜欢使用这些值。
这里是Review 模型关系。
public function plugin()
{
return $this->belongsTo(Plugin::class, "product_id")->withDefault();
}
public function module()
{
return $this->belongsTo(Module::class, "product_id")->withDefault();
}
public function service()
{
return $this->belongsTo(Service::class, "product_id")->withDefault();
}
public function getItem()
{
if($this->product_type=='module')
{
return $this->module;
}elseif($this->product_type=='service')
{
return $this->service;
}else {
return $this->plugin;
}
}
现在我想在 Review Model 中通过预先加载来获得它们,如下所示:
$reviews = Review::with("getItem")->get();
如果没有 Eager 加载,我可以使用 $review->getItem()->name // 这会返回产品名称。
如何通过急切加载获得它们?
【问题讨论】:
标签: php laravel eloquent polymorphism laravel-relations