mysql - Laravel Eloquent 地获取数据库列中最常见的值

标签 mysql laravel eloquent laravel-5.4

在表 animals 中,我在 animal_name 列中有以下值

猫 狗 猫 我想从中提取猫这个词,因为它是该专栏中最流行/最常用的词。我如何使用 Laravel Eloquent 做到这一点?

最佳答案

Eloquent :

App\Animal::select('name')
    ->groupBy('name')
    ->orderByRaw('COUNT(*) DESC')
    ->limit(1)
    ->get();

输出:

=> Illuminate\Database\Eloquent\Collection {#711
     all: [
       App\Animal {#725
         name: "cat",
       },
     ],
   }

Same thing with Query Builder:

DB::table('animals')
    ->select('name')
    ->groupBy('name')
    ->orderByRaw('COUNT(*) DESC')
    ->limit(1)
    ->get();

输出:

=> Illuminate\Support\Collection {#734
     all: [
       {#738
         +"name": "cat",
       },
     ],
   }

Any way to also fetch the "cat" count in the same query?

Sure there is

App\Animal::select('name')
    ->selectRaw('COUNT(*) AS count')
    ->groupBy('name')
    ->orderByDesc('count')
    ->limit(1)
    ->get();
=> Illuminate\Database\Eloquent\Collection {#711
     all: [
       App\Animal {#725
         name: "cat",
         count: 123
       },
     ],
   }

关于mysql - Laravel Eloquent 地获取数据库列中最常见的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44894294/

相关文章:

Mysql 时间记录为 Unixtime 而不是 Mysql Timestamp

java - 没有合适的驱动程序错误

php - Laravel5:什么更好,类名作为字符串或 Classname::class

php - Laravel PayPal 支付返回 400

php - Laravel Eloquent 5 表

PHP: try catch 异常

PHP 从一种表单更新数据库上的不同字段

php - 如何在 Laravel 4 中查询 min( created_at )?

mysql - Laravel Eloquent 独特的时间戳年份

php - Laravel Eloquent join vs with