Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql orderBy最常出现但返回所有行_Mysql_Laravel_Eloquent - Fatal编程技术网

Mysql orderBy最常出现但返回所有行

Mysql orderBy最常出现但返回所有行,mysql,laravel,eloquent,Mysql,Laravel,Eloquent,我基本上是根据结果中出现最多的item\u id对我的收藏进行排序 比如,;我得到了一个包含以下数据的表格: +----+---------+---------+---------+---------+ | id | item_id | column2 | column3 | column4 | +----+---------+---------+---------+---------+ | 1 | 12 | Hi | DataHere| MoreData| | 2 |

我基本上是根据结果中出现最多的
item\u id
对我的收藏进行排序

比如,;我得到了一个包含以下数据的表格:

+----+---------+---------+---------+---------+
| id | item_id | column2 | column3 | column4 |
+----+---------+---------+---------+---------+
| 1  | 12      | Hi      | DataHere| MoreData|
| 2  | 12      | Hi      | DataHere| MoreData|
| 3  | 14      | Hi      | DataHere| MoreData|
| 4  | 13      | Hi      | DataHere| MoreData|
| 5  | 12      | Hi      | DataHere| MoreData|
| 6  | 21      | Hi      | DataHere| MoreData|
+----+---------+---------+---------+---------+
我将如何使用一个简单的
MyData::get()
model&accessor访问初始表

我已尝试执行以下操作,但只能返回
项目id
计数
,我需要返回所有列,仅按最频繁的
项目id
排序

MyData::select(\DB::raw('item_id'), \DB::raw('count(*) as count'))->having('item_id', '>', '0')->groupBy('item_id')->orderBy('count', 'desc')->get();
我的预期结果是:

+----+---------+---------+---------+---------+
| id | item_id | column2 | column3 | column4 |
+----+---------+---------+---------+---------+
| 1  | 12      | Hi      | DataHere| MoreData|
| 2  | 12      | Hi      | DataHere| MoreData|
| 5  | 12      | Hi      | DataHere| MoreData|
| 6  | 21      | Hi      | DataHere| MoreData|
| 3  | 14      | Hi      | DataHere| MoreData|
| 4  | 13      | Hi      | DataHere| MoreData|
+----+---------+---------+---------+---------+

您可以在DB.raw内部进行查询,例如:
DB::select(DB::raw(“从程序p中选择p.name,part.*,其中p.id=part.id”)

这应该可以:

$table = app(MyData::class)->getTable();
MyData::selectRaw("*, (select count(*) from $table t where t.item_id = $table.item_id) as count")
    ->orderBy('count', 'DESC')
    ->get();
您可以将第一行和
$table
替换为实际的表名。和
*
,选择您真正想要选择的字段

事实上,如果您不需要选择中的
计数
,您可以执行以下操作:

$table = app(MyData::class)->getTable();
MyData::orderByRaw("(select count(*) from $table t where t.item_id = $table.item_id) DESC")
    ->get();