Laravel eloquent get most common value in a database column

孤街醉人 提交于 2019-12-12 14:18:36

问题


From a table animals I have the following values in the animal_name column

cat dog cat I want to pull the word cat from that because it is the most popular/common word in that column. How do I do that using laravel eloquent?


回答1:


Eloquent:

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

Output:

=> 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();

Output:

=> 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
       },
     ],
   }


来源:https://stackoverflow.com/questions/44894294/laravel-eloquent-get-most-common-value-in-a-database-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!