Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Laravel eloquent erhält den häufigsten Wert in einer Datenbankspalte

Eloquent:

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

Ausgabe:

=> Illuminate\Database\Eloquent\Collection {#711
     all: [
       App\Animal {#725
         name: "cat",
       },
     ],
   }

Dasselbe gilt für den Abfragegenerator:

DB::table('animals')
    ->select('name')
    ->groupBy('name')
    ->orderByRaw('COUNT(*) DESC')
    ->limit(1)
    ->get();

Ausgabe:

=> Illuminate\Support\Collection {#734
     all: [
       {#738
         +"name": "cat",
       },
     ],
   }

Sicher gibt es

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