从表animals
我在animal_name
列
cat
dog
cat
我想从中提取单词cat,因为它是该列中最受欢迎/常用的单词。如何使用laravel eloquent来做到这一点?
答案 0 :(得分:10)
锋:
App\Animal::select('name')
->groupBy('name')
->orderByRaw('COUNT(*) DESC')
->limit(1)
->get();
输出:
=> Illuminate\Database\Eloquent\Collection {#711 all: [ App\Animal {#725 name: "cat", }, ], }
查询生成器也是如此:
DB::table('animals')
->select('name')
->groupBy('name')
->orderByRaw('COUNT(*) DESC')
->limit(1)
->get();
输出:
=> Illuminate\Support\Collection {#734 all: [ {#738 +"name": "cat", }, ], }
还可以在同一个查询中获取“cat”计数吗?
当然有
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 }, ], }