Laravel中AreaBlocks模型多态关联返回null问题求助
解决Eloquent morphTo() 返回null的问题
你遇到的问题其实是字段名不匹配导致的——Eloquent的morphTo关联有默认的命名规则,它会自动寻找{关联名}_type和{关联名}_id这两个字段,但你的数据库里用的是owner_type和owner_id,字段名不匹配所以关联加载失败,返回了null。
修复步骤:
修改你的block关联方法,明确指定morphTo对应的type和id字段:
public function block() { // 参数分别是:关联名称(可选,用__FUNCTION__可以直接取方法名)、type字段名、id字段名 return $this->morphTo(__FUNCTION__, 'owner_type', 'owner_id'); }
或者更简洁的写法(不需要指定关联名称时):
public function block() { return $this->morphTo(null, 'owner_type', 'owner_id'); }
完整的AreaBlocks模型示例:
<?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(__FUNCTION__, 'owner_type', 'owner_id'); } }
验证效果
现在重新访问你的路由:
Route::get('/', function(){ return App\Models\AreaBlocks::all(); });
返回的每条AreaBlocks记录里,block字段就会正确加载对应owner_type和owner_id的模型数据了。
额外说明(可选)
如果需要在关联模型(比如Title、Textarea)里定义反向关联,可以添加morphMany方法:
// 在App\Models\Title模型中 public function areaBlocks() { return $this->morphMany(AreaBlocks::class, 'block', 'owner_type', 'owner_id'); }
内容的提问来源于stack exchange,提问作者user0129e021939232
相关产品推荐
相关产品推荐

