You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中Post、Advisor与Comment模型的关联关系正确编写方法

解决方案

你当前的场景属于Laravel一对多多态关联的典型使用场景,因为comments表通过related_id(关联资源ID)和type(关联资源模型类名)两个字段关联不同模型,不能用普通的hasMany/belongsTo实现,需要按如下方式改写关联方法:


1. 改写Post模型关联(app/Models/Post.php)

public function comments()
{
    // 手动指定多态关联的类型字段为type、关联ID字段为related_id
    return $this->morphMany(Comment::class, 'commentable', 'type', 'related_id');
}

2. 改写Advisor模型关联(app/Models/Advisor.php)

和Post模型的关联逻辑完全一致:

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable', 'type', 'related_id');
}

3. 改写Comment模型关联(app/Models/Comment.php)

如果你需要同时支持$comment->post、$comment->advisor和通用多态调用$comment->commentable(自动返回对应类型的资源实例),可以同时写三个关联方法:

/**
 * 通用多态关联,调用时自动返回对应Post/Advisor实例
 */
public function commentable()
{
    return $this->morphTo('commentable', 'type', 'related_id');
}

/**
 * 直接获取评论所属的文章,非文章类型的评论返回null
 */
public function post()
{
    return $this->belongsTo(Post::class, 'related_id')
        ->where('type', Post::class);
}

/**
 * 直接获取评论所属的评测,非评测类型的评论返回null
 */
public function advisor()
{
    return $this->belongsTo(Advisor::class, 'related_id')
        ->where('type', Advisor::class);
}

效果验证

修改后即可满足你的所有需求:

  • Post::find(1)->comments 会返回ID为1的文章对应的2条评论
  • Advisor::find(1)->comments 会返回ID为1的评测对应的1条评论
  • 属于文章的评论调用$comment->post会返回对应文章实例,调用$comment->advisor返回null
  • 属于评测的评论调用$comment->advisor会返回对应评测实例,调用$comment->post返回null

内容的提问来源于stack exchange,提问作者Maik Lowrey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 02:15:07