Laravel 在 withCount 方法上使用 where 子句

新手上路,请多包涵

我正在尝试使用这段代码对 laravel 雄辩的查询构建器的 withCount 方法执行 where 子句。

 $posts = Post::withCount('upvotes')->where('upvotes_count', '>', 5)->get();

这段代码给了我这个错误。

SQLSTATE [42S22]:未找到列:1054 ‘where 子句’中的未知列’upvotes_count’(SQL:选择,(从 upvotes 选择计数(upvoteable_id 其中 upvotes --- = posts . id and upvotes . upvoteable_type = App\Post) as upvotes_count from posts 其中 upvotes_count > 5)

所以据我猜测,没有选择 upvotes_count ,因此没有找到该列,但是如果我执行这段代码。

 $posts = Post::withCount('upvotes')->get();

然后我得到这个输出。

 {
"id": 1,
"user_id": 15,
"title": "Voluptatum voluptas sint delectus unde amet quis.",
"created_at": "2016-10-07 13:47:48",
"updated_at": "2016-10-07 13:47:48",
"upvotes_count": 7
},
{
"id": 2,
"user_id": 2,
"title": "Molestiae in labore qui atque.",
"created_at": "2016-10-07 13:47:48",
"updated_at": "2016-10-07 13:47:48",
"upvotes_count": 2
},

这基本上意味着正在选择 upvotes_count,因此我对如何解决这个问题感到非常困惑。

(到目前为止我尝试的更多选项在下面给出了与之相关的相应错误。)

 $posts = Post::where('id', $id)->withCount(['upvotes' => function($query) {
        $query->where('upvotes_count', '>', 5);
    }])->get();

错误。

SQLSTATE [42S22]:找不到列:1247 不支持引用“upvotes_count”(项目列表中的前向引用)(SQL:选择,(从 upvotes 选择计数( )—其中 upvotesupvoteable_id = posts . id and upvotes . upvoteable_type = App\Post and upvotes_count > 5) 作为 upvotes_count 来自 posts 其中 id = 1)

代码。

 $posts = Post::where('id', $id)->with(['upvotes' => function($query) {
        $query->select('upvoteable_id AS upvotes_count');
    }])->where('upvotes_count', '>', 5)->get();

$posts = \App\Post::where('id', $id)->with(['upvotes' => function($query) {
        $query->selectRaw('upvoteable_id AS upvotes_count');
    }])->where('upvotes_count', '>', 5)->get();

错误。

SQLSTATE [42S22]:未找到列:1054 ‘where 子句’中的未知列 ‘upvotes_count’(SQL:select * from posts 其中 id = 1 和 upvotes_count > 5)


我只想在与父模型有关系的 count() 方法上使用 where 子句。

原文由 slapbot 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

您可以使用以下方法实现请求的结果:

 $posts = Post::withCount('upvotes')
         ->having('upvotes_count', '>', 5)
         ->get();

原文由 Medin Piranej 发布,翻译遵循 CC BY-SA 3.0 许可协议

另一种好方法是我们可以单独过滤它,甚至为该列名分配一个别名

$posts = Post::withCount([
    'upvotes',
    'upvotes as upvotes_count' => function ($query) {
        $query->where('upvotes_count', '>', 5);
    }])
    ->get();

现在在刀片中你可以做

$posts->upvotes_count

原文由 Yousef Altaf 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题