首页 > 解决方案 > Laravel:通过多态关系从子级访问父级时未定义的属性

问题描述

我有三个模型:StoreLabInventory。库存可以通过多态关系属于任何一个。

class Store extends Model
{
    public function inventory()
    {
        return $this->morphOne(\App\Models\Inventory::class, 'keeper');
    }
}


class Lab extends Model
{
    public function inventory()
    {
        return $this->morphOne(\App\Models\Inventory::class, 'keeper');
    }
}


class Inventory extends Model
{
    protected $appends = ['keeper'];

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

    public function getKeeperAttribute()
    {
        return $this->keeper;
    }
}

当我尝试使用“keeper”属性从 Inventory 实例访问父级时,我得到了这个

Undefined property: App\\Models\\Inventory::$keeper

我有keeper_idkeeper_type在我的inventories表和数据插入与附加的关系很好。

Schema::create('inventories', function (Blueprint $table) {
        $table->id();
        $table->string('name')->nullable();
        $table->unsignedBigInteger('keeper_id')->nullable();
        $table->string('keeper_type')->nullable();
        $table->timestamp('created_at')->useCurrent();
        $table->timestamp('updated_at')->nullable()->useCurrentOnUpdate();
});

dd($this->keeper());正确返回关系:

Illuminate\Database\Eloquent\Relations\MorphTo {#1326 ▼
  #morphType: "keeper_type"
  #models: null
  #dictionary: []
  #macroBuffer: []
  #morphableEagerLoads: []
  #morphableEagerLoadCounts: []
  #morphableConstraints: []
  #child: App\Models\Inventory {#1302 ▶}
  #foreignKey: "keeper_id"
  #ownerKey: "id"
  #relationName: "keeper"
  #query: Illuminate\Database\Eloquent\Builder {#1321 ▶}
  #parent: App\Models\Inventory {#1302 ▶}
  #related: App\Models\Store {#1305 ▶}
  #withDefault: null
}

那么为什么不$this->keeper;工作呢?可能是什么问题呢?

标签: phplaraveleloquentpolymorphic-associations

解决方案


推荐阅读