从表animals中,我在animal_name列中具有以下值
cat dog cat我想从中拉出cat一词,因为它是该列中最流行/最常用的词。我该如何使用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",
       },
     ],
   }

Sure there is

App\Animal::select('name')
    ->selectRaw('COUNT(*) AS count')
    ->groupBy('name')
    ->orderByDesc('count')
    ->limit(1)
    ->get();

=>照亮\数据库\ Eloquent \集合{#711
全部: [
App\Animal {#725
名称:“猫”,
数:123
},
],
}

关于mysql - Laravel Eloquent 地在数据库列中获得最普遍的值(value),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44894294/

10-16 16:19