我的数据库中有如下表:
table area_blocks;
id
owner_type
owner_id
created_at
updated_at
在owner_type
字段中,它具有Eloquent Model名称,owner_id
是数据库中该模型的id。示例:
db: area_blocks
id | owner_type | owner_id
1 | App\Models\Title | 3
2 | App\Models\Title | 4
3 | App\Models\Textarea | 1
因此,我希望当我获取所有这些内容时,还要急切加载owner_type
中存储的雄辩模型中的相关字段。
是否存在雄辩的关系,可以使用急切加载从owner_type字段中恢复该记录?我试过$this->morphTo()
,例如
public function block()
{
return $this->morphTo();
}
但是会以null
的形式返回。有什么想法可以做到这一点?
示例代码;
<?php
namespace App\Models;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class AreaBlocks extends Model
{
protected $with = ['block'];
public function block()
{
return $this->morphTo();
}
}
Route::get('/', function(){
return App\Models\AreaBlocks::all();
});
答案 0 :(得分:2)
您必须指定列名称/前缀:
public function block()
{
return $this->morphTo('owner');
}
或重命名关系:
public function owner()
{
return $this->morphTo();
}