能否自定义Laravel Eloquent morphToMany的name_type字段?
自定义多态关联的类型字段
嘿,刚好碰到过类似的需求,我来给你捋清楚怎么处理~
先说说 morphMany 的自定义方式
我们可以直接参考官方文档示例,自定义 morphMany 的 $type 参数,它的方法签名是:
public function morphMany($related, $name, $type = null, $id = null, $localKey = null)
举个实际例子:如果传递第三个参数 $type 为 commentable_object,就能把 comments 表中的默认 commentable_type 字段替换成 commentable_object(对应的表结构:id - integer、body - text、commentable_id - integer、commentable_type - string)。
重点解决 morphToMany 无 $type 参数的问题
因为 morphToMany 是多对多的多态关联,它的构造方法里没有直接暴露 $type 参数,但我们可以通过两种方式自定义类型字段:
方式一:直接修改关联实例的属性
这是最简便的方法,不需要额外创建类,在调用 morphToMany 后直接设置关联实例的 morphType 属性就行:
public function tags() { $relation = $this->morphToMany(Tag::class, 'taggable'); // 把默认的`taggable_type`改成你想要的字段名,比如`taggable_object` $relation->morphType = 'taggable_object'; return $relation; }
方式二:创建自定义的关联类
如果需要在多个模型里复用这个自定义规则,可以创建一个继承自 MorphToMany 的类,重写构造方法来指定默认的类型字段:
use Illuminate\Database\Eloquent\Relations\MorphToMany; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; class CustomMorphToMany extends MorphToMany { public function __construct(Builder $query, Model $parent, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName = null, $type = null) { // 这里可以自定义默认的类型字段名,比如把`{$name}_type`改成`{$name}_object` $type = $type ?? "{$name}_object"; parent::__construct($query, $parent, $name, $table, $foreignPivotKey, $relatedPivotKey, $parentKey, $relatedKey, $relationName); // 直接设置morphType属性 $this->morphType = $type; } }
然后在模型里使用这个自定义关联类:
use App\CustomMorphToMany; use App\Models\Tag; class Post extends Model { public function tags() { return new CustomMorphToMany( $this->newQuery(), $this, 'taggable', 'taggables', 'taggable_id', 'tag_id', 'id', 'id', null, 'taggable_object' // 也可以手动传入自定义的类型字段名 ); } }
内容的提问来源于stack exchange,提问作者Des
相关产品推荐
相关产品推荐

