求解决 Laravel with () limit 的问题 附带解决方案

比如如何取得每篇文章中的前10条评论
下面为错误写法:

essay::with(['comment' => function($query) {
    $query->take(10)
}])

谢谢各位大佬的帮助!
但是最终效果都不理想。
https://github.com/laravel/framework/issue...
在上面的issues找到解决方法
贴一下自己的代码

//这里我是反向关联,正向关联也可以的。
public function products()
{
    return $this->belongsToMany(Hproduct::class,'hproduct_has_type','type_id','product_id');
}

public function topTenproducts()
{
    return $this->products()->with('supplier')->where('is_sale','=',1)->limit(4);
}

public function getProdcutsWithtopTenproducts($col)
{
    $model = $this->whereIn('id',$col)->get();
    $model->each(function ($model) {
        $model->load('topTenproducts');
        });
    return $model->toArray();
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 22

貌似只能在模型内。


public function comment() 
{
        return $this->hasMany('Comment')->take(10);
}
5年前 评论

@doobi 这个设置也不对的,我设置了8个,结果就是一篇文章下面3个,第二篇文章就是5个,凑满了8个

5年前 评论

mysql 搞不定..

简单业务,就是,每一个文章下面读取N条评论

5年前 评论

@dope2008 大佬是怎么解决的

5年前 评论

@dope2008 不能这么写的。代码审查

5年前 评论
$essay->comments()->take(10)->get();
5年前 评论

@Insua 这样不是循环了吗

5年前 评论
DianWang

这样?

  public function replies()
    {
        return $this->hasMany(Reply::class);
    }

    public function topTenReplies()
    {
        return $this->replies()->limit(10);
    }

    public function getArticlesWithTenReplies()
    {
        return $this
            ->with('topTenReplies')
            ->get();
    }
5年前 评论
App::whereHas('comment', function ($query) {
    $query->take(10);
})-with(['comment']);
5年前 评论

@全场我最姜姜姜丶 最终结果,你看看多少条SQL,不是一样吗?

5年前 评论

@DianWang 最后是怎么调用的,大佬。

5年前 评论

@AGD 关联的查询,会影响查询速度

5年前 评论
DianWang

@全场我最姜姜姜丶 这些是在模型里定义的,你直接在控制器里或者需要的地方实例化模型然后调用不就行了。。

5年前 评论

@DianWang 好!,我知道了,一时间没转过来。谢谢

5年前 评论

@dope2008 嗯,我看一下最后的sql,谢谢了。

5年前 评论

@Gasg 老哥是最正确。感谢

5年前 评论

我也是这么写的

$themes = Theme::where('is_open', true)->get();
$themes->each(function($theme) use ($limit) {
     $theme->load(['products' => function ($query) use ($limit) {
            $query->limit($limit)->orderBy('created_at');
     }]);
});

其实跟你的答案都一样,我没去看数据库查询记录,但我感觉这种写法应该是一种n+1的写法,先循环出每个$theme,然后加载每个$theme关联的product。当$theme数据多的时候,应该会非常慢

4年前 评论
全场我最姜姜姜丶 (楼主) 4年前

避免不了N+1吗?

3年前 评论
全场我最姜姜姜丶 (楼主) 3年前

我也遇到了这个问题,找到了这个解决方案 laravel.io/forum/04-05-2014-eloque... 最后一条评论。

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!