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
// 这会返回产品名称。
如何通过急切加载获得它们?