Laravel 版本:7.0
reviews表 (Model - Review) 有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();
如果没有急切加载,我可以使用$review->getItem()->name// 这会返回产品名称。
如何通过急切加载获得它们?