可用:后模型
id - integer
title - string
body - text
评论模型
id - integer
body - text
post_id - integer
commentable_type - string
评论就是按照这个态度配置的
public function post(): BelongsTo
{
return $this->belongsTo(Post::class);
}
public function expansion(): MorphTo
{
return $this->morphTo();
}
重要的是,如果在正常的多态关系中,commentable_type 表示父模型,post_id 表示模型标识符,那么一切都会变得更加复杂。post_id确实指向父模型的标识符,但commentable_type字段中指定的模型本身指的是数据库中不存在的子模型CommentChildOne和CommentChildTwo。这些只是扩展基本评论的某种合成模型。
如果我在 Post 中建立常规连接
public function comments(): hasMany
{
return $this->hasMany(Comment::class, 'post_id');
}
然后我得到了所需的记录,但它们是Comment类型的。是否可以构建这样的多态关系来获取子模型CommentChildOne、CommentChildTwo?
也许这对某人有用。不可能实现标准关系;重写 Laravel 也不是所需的方法。由于 CommentChildOne CommentChildTwo 是 Comment 类的综合子类(不在数据库中)。然后它们具有与父级相同的属性和方法。因此,在 Post 类中,创建了 2 个函数来查找给定记录的记录。