首页 文章

Laravel变量模型多态

提问于
浏览
0

我的数据库中有如下表:

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();
});

1 回答

  • 2

    您必须指定列名称/前缀:

    public function block()
    {
        return $this->morphTo('owner');
    }
    

    或重命名关系:

    public function owner()
    {
        return $this->morphTo();
    }
    

相关问题