首页 > 解决方案 > Laravel variable model polymorphic

问题描述

I have a table as follows in my database:

table area_blocks;

id
owner_type
owner_id
created_at
updated_at

in the owner_type field it has the Eloquent Model name and the owner_id is the id of that model in the database. Example:

db: area_blocks

id | owner_type            | owner_id 
1  | App\Models\Title      | 3 
2  | App\Models\Title      | 4
3  | App\Models\Textarea   | 1

So I'm expecting when I fetch all of these to also eager load the relevant field from the eloquent model stored in owner_type.

Is there an eloquent relationship that can bring back that record from the owner_type field using eager loading? I've tried $this->morphTo(), e.g.

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

but that is returned as null. Any ideas how this can be done?

Example code;

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

标签: phplaravellaravel-5eloquentrelationship

解决方案


您必须指定列名/前缀:

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

或重命名关系:

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

推荐阅读