Laravel eloquent在数据库专栏中获得最常见的价值

时间:2017-07-03 21:52:36

标签: mysql laravel eloquent laravel-5.4

从表animals我在animal_name

中有以下值

cat dog cat 我想从中提取单词cat,因为它是该列中最受欢迎/常用的单词。如何使用laravel eloquent来做到这一点?

1 个答案:

答案 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
       },
     ],
   }