在表 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/