首页 > 解决方案 > Laravel - Eloquent 如何建立这种关系 HasMany -> BelongToThrough

问题描述

我怎么能想出这种关系呢?

User:
 - id
 - name
 - username

Post
 - id
 - user_id
 - comment_id

Coment
 - id
 - other_id

Other
 - id
 - name
 - descripton

所以关系应该是:
User - belongsToMany -> Post - belongsTo -> Comment - belongsTo -> Other

在这个关系中,user有很多职位,但comment_id关系是属于的。我不能使用 hasManyThrough 因为关系不同。

有没有办法使这项工作?它应该是 hasMany -> BelongsToThrough

我可以使用 hasMany 然后在每个项目上调用 BelongsTo,但我的关系太深了。

它需要一个可以使用 hasMany 然后 belongsToThrough 这样的关系的关系

更新
有一个belongsToMany而不是hasMany,但仍然不确定我是否可以解决这个问题

有替代解决方案

class User {
 
    public function user_post_comments () {
        return $this->belongsToMany(Post::class);
    }

    public function getCommentsAttribute() {
        return $this->user_post_comments->map(function ($value, $key) {
            $obj = $value->comment;
            $obj->pivot=(object) [
                // Extra variable for the nested 
            ];
            return $obj;
        });
    }
}
class Post {
    
    public function comment () {
        return $this->belongsTo(Comment::class);
    }
}

$this->user->comments将返回帖子评论而不是帖子

标签: laravelrelation

解决方案


https://laravel.com/docs/8.x/eloquent-relationships#has-many-through

您可以像这样从用户那里获得评论

class User extends Model
{
    /**
    * Get all of the Comments for the Post.
    */
    public function comments()
    {
     return $this->hasManyThrough(Comment::class, Post::class);
    }

    /**
    * Get all of the Post.
    */
    public function posts()
    {
     return $this->hasMany(Post::class);
    }
}

像这样获取其他人的评论

   class Comment extends Model
   {
      
       public function others()
       {
         return $this->belongsTo(Other::class);
       }
   }

并得到这样的最终数据

$data = User::with(['comments.others'])->get();

推荐阅读