php - Laravel:通过多态关系从子级访问父级时未定义的属性
问题描述
我有三个模型:Store、Lab和Inventory。库存可以通过多态关系属于任何一个。
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_id
和keeper_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;
工作呢?可能是什么问题呢?
解决方案
推荐阅读
- java - Java如何将新的空列添加到下载的CSV
- javascript - 获取元素 HTML
- telegram - 可以在浏览器中使用电报身份验证 SDK
- javascript - 有没有办法在网站顶部更改菜单文本颜色
- html - 使用标记生成器格式化 html 表格
- batch-file - 打开包含变音符号的 URL 和批处理
- python - Python在文件中拆分行时,最后会留下换行符
- c# - 将 PrinterSettings 序列化为字符串或 blob 以插入数据库
- unity3d - 在统一 2d for mobile 中将按钮组件添加到 2d sprite
- javascript - 读取在内容脚本文件 Chrome 扩展之外写入的 JSON