php - 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();
});
解决方案
您必须指定列名/前缀:
public function block()
{
return $this->morphTo('owner');
}
或重命名关系:
public function owner()
{
return $this->morphTo();
}
推荐阅读
- node.js - 如何在铬中传递身份验证令牌
- python - users.models.Profile.user.RelatedObjectDoesNotExist:配置文件没有用户
- python - Python tkinter 不能使用 Entry.get() 函数
- angularjs - 关于如何根据字段值重复 ng-repeat 中的表,我有这个问题
- html - 悬停动画反弹
- javascript - 摆脱 html 元素 - React
- r - X 必须是一个数值
- node.js - router.get 发送 res 两次
- php - 在 laravel 控制器中访问中间件
- php - 如何使用 str_split() 函数逐字符打印字符串