php - 仅获取具有最新一条评论且声誉超过 5 条的帖子
问题描述
我有 $posts 集合实例,我不会只得到那些有评论的帖子,而最新的一条评论有更多的 5 名声。我的收藏实例与此类似
[
[
'id' => 1,
'title' => 'Some title',
'comments' => [
[
'id' => 1,
'content' => 'some content',
'reputation' => 5
],
[
'id' => 2,
'content' => 'some content',
'reputation' => 6
],
...
],
],
...
]
我的代码是
$posts = $posts->filter(function ($post, $key) {
$isHasMoreFiveComments = false;
foreach ($post['comments'] as $comment) {
if ($comment['reputation'] > 5) {
$isHasMoreFiveComments = true;
break;
}
}
return $isHasMoreFiveComments;
});
但我认为还有更好的解决方案。
解决方案
我不确定你想在这里做什么,但可能这对你有用?
波纹管将检索至少有 1 条评论且声誉为 5 及以上的帖子,并且它也是按降序排列的。
$posts = Post::whereHas('comments')->with(['comments'=>function($q){
$q->where('reputation', '>', 4);
$q->orderBy('id', 'desc');
}])->get();
注意:您必须commments
在Post
模型中初始化关系
前任:
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
推荐阅读
- java - 在 Java 中实现文件身份验证的最佳方法是什么?
- maven - 如何使用 gmavenplus 运行的 groovy 脚本设置 maven 项目属性?
- javascript - 选择单选按钮时显示的 div 标签
- anaconda - conda 环境中的屏幕不起作用
- c# - C# .NET 将 Action 作为方法的参数,该方法提供可以从 lambda 实例化此 Action 执行的函数
- javascript - 比较工作表名称的 Google 脚本在应该返回 True 时返回 False
- c - 复杂模式 C 的 fnmatch 用法
- docker - 如何从命令行运行 VIsual Studio Docker 容器?适用于VS,但不适用于命令行
- android - 缓存中的 File.delete 不起作用 Android
- swift - 如何保持 UIButton 的图像颜色不会重置为默认值?