【发布时间】:2018-05-29 13:16:03
【问题描述】:
我的数据库中有一个如下表:
table area_blocks;
id
owner_type
owner_id
created_at
updated_at
在owner_type 字段中,它具有 Eloquent 模型名称,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 中的 eloquent 模型中急切加载相关字段。
是否有一种雄辩的关系可以使用预先加载从 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();
});
【问题讨论】:
-
您有什么疑问?
block()定义在什么模型中? -
我已经更新了上面的完整代码。 Block 没有模型,我希望它从 db @JonasStaudenmeir 中的 owner_type 字段中获取模型,因此例如 area_blocks.id=1 将具有 $area_block->block 将是 App\Models\ 的数据库记录标题.id = 1
标签: php laravel laravel-5 eloquent relationship