gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:47:07 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com