duanjianhe1388 2017-08-05 14:05 采纳率: 100%
浏览 7

在查询生成器上运行集合方法

Lets say I have a Post object. I want the starred ones to subsequently filter them based on some conditions.

For some years I kept doing it this way:

Post::where('is_starred', true)->get()->filter(function($post){ 
    ... 
});

This works great but today I found out that even if I remove the get() call it still works. I don't know exactly why this works because where() returns a QueryBuilder and filter() is a collection method. The same happens if instead a filter() I call some other collection methods like each().

Post::where('is_starred', true)->filter(function($post){ 
    ... 
});

So my question is: Can collection methods be applied to QueryBuilder? Why? I looked at the QueryBuilder class to find out how these methods can be applied there but I didn't find anything. Is there something about that in Laravel's documentation?

  • 写回答

1条回答 默认 最新

  • dongruyan4948 2017-08-05 15:33
    关注

    It was my fault. This kind of behavior happens with each() but filter(). Eloquent\Builder has an each() method which in its implementation has a call to chunk() which executes get() and apply the callback to each element.

    It would be interesting to have the same for filter(), wouldn't it?

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100