【问题标题】:Limit on comment (hasMany relation with Post model) for each post in LaravelLaravel 中每个帖子的评论限制(与 Post 模型有很多关系)
【发布时间】:2017-10-04 14:22:44
【问题描述】:

我试图限制 laravel 中的 hasMany 关系,但不是每个帖子,而是限制整个或所有记录。下面是我的解释代码。

 class Post extends Model {


    protected $table = "user_posts";
    protected $appends = ['logged_in_user_id', 'comments_count'];

    public function user() {
        return $this->belongsTo('App\User');
    }

    public function comments() {
        return $this->hasMany('App\Comment')->take(2);
    }
}

我正在尝试在每个帖子上获得 2 或 3 条最新评论,如下所示

$posts = \App\Post::orderBy('updated_at', 'DESC')->with('comments')->where('user_posts.user_id', $user_id)->paginate(10);

问题不是为每个帖子提供 2 条评论,而是从所有获取的帖子中只提供 2 条评论。

当前结果:

帖子1:

  1. 评论1
  2. 评论2

帖子2: 帖子 2 中没有加载评论,因为它限制了整体。

预期:

post1:

  1. 评论1
  2. 评论2

post2:

  1. 评论1
  2. 评论2

【问题讨论】:

  • 试试这个\App\Post::orderBy('updated_at', 'DESC')->with(['comments' => function($q) { $q->take(2); }])->get(); !!
  • 我试过了,但我给出了相同的结果
  • 明显的问题 post2 有 cmets 吗??
  • 是的 id 确实有

标签: php laravel laravel-5 eloquent


【解决方案1】:

在尝试这个之前我已经做过类似的事情

 public function comments(){
    return $this->hasMany(Comment::class, 'post_id')->latest()->limit(4);
}

您还可以为 Post 模型添加一个全局范围,以便它总是像这样急切地加载 4 个 cmets:

 static::addGlobalScope('comments', function ($builder){
        $builder->with('comments');
    });

所以您在 Post.php 中的引导方法应该如下所示:

protected static function boot()
{
    parent::boot();

    static::addGlobalScope('comments', function ($builder){
        $builder->with('comments');
    });

}

因此你可以这样查询:

$posts = \App\Post::orderBy('updated_at', 'DESC')->where('user_posts.user_id', $user_id)->paginate(10);

更新:

当我们这样查询时它不起作用

$posts = \App\Post::orderBy('updated_at', 'DESC')->where('user_posts.user_id', $user_id)->paginate(10);

因为限制只应用一次。检查 github 问题https://github.com/laravel/framework/issues/4835。然而,这是一个可能的解决方案https://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/

希望对你有帮助:)

【讨论】:

  • 感谢您的回复,但它的作用相同。我有 5 个帖子,每个帖子都有 cmets,但它只为所有 5 个相应的帖子加载 4 cmets...它应该为每 5 个帖子加载 4 条评论
  • @SainishMomin 嗯嗯,奇怪,cmets 表上帖子的外键是什么?
  • post_id 是评论表的外键
  • @SainishMomin 好的,你可以尝试加载 2 个帖子吗,像这样 ==> App\Post::latest()->take(2)->get() 只是为了验证它是否加载cmets 正确
  • 是的,我尝试加载 2 个帖子,它加载正确,因为第一个帖子有 2 条评论,第二条也有 2 条评论。因此,我们在模型中限制了总共 4 条评论
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 2017-04-03
  • 2016-08-04
  • 1970-01-01
  • 2021-06-24
  • 2014-05-10
  • 1970-01-01
相关资源
最近更新 更多