php - 拉维尔 : How to count in query

标签 php mysql laravel laravel-5 eloquent

我有以下查询:

App\User::join('gift_sents', function($builder){
      $builder->on('gift_sents.receiver_id', '=', 'users.id');
      })
      ->select('users.*', 'COUNT(gift_sents.receiver_id as total_posts')
      ->groupBy('gift_sents.id')
      ->orderBy('total_posts', 'ASC')
      ->limit(3)->get();

计数不起作用,它应该起作用!

出现以下错误:

未找到列:1054 未知 “字段列表”中的“COUNT(gift_sents.receiver_id”列(SQL:选择用户。*,COUNT(gift_sents receiver_idastotal_postsfromusersinner joingift_sentsongift_sents.receiver_id=用户.idgroup bygift_sents.idorder bytotal_postsasc limit 3)

最佳答案

我认为应该是:

  ->select('users.*', DB::raw('COUNT(gift_sents.receiver_id) as total_posts'))

参见文档 here - “原始表达式”部分

关于php - 拉维尔 : How to count in query,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414508/

相关文章:

php - 未捕获的 PHP 异常 Symfony\Component\HttpKernel\Exception\NotFoundHttpException : "No route found for "GET/"

php - 如何重定向到(或强制执行)SSL 连接?

php - SQL查询在数据库中运行,但在PHP中显示 "undefined index"

html - 将html颜色表保存在mysql中

php - 如何从图像结果列表中选择一张图像?

PHP MySQL 查询数组帮助

PHP MySQL,查询错误

mysql - 将参数传递给 MySQL 脚本命令行

php - 在我的编辑器中管理上传文件的最佳方式?

php - Laravel 5分组仅显示第一行