我基本上要做的是根据结果中最常出现的item_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()
模型&存取器。
我尝试过以下操作,但只能获得item_id
&要返回count
,我需要返回所有列,只需按最常见的item_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|
+----+---------+---------+---------+---------+
答案 0 :(得分:1)
这应该有效:
$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
替换为实际的表名。并*
包含您实际想要选择的字段。
事实上,如果您在选择中不需要count
,那么您可以这样做:
$table = app(MyData::class)->getTable();
MyData::orderByRaw("(select count(*) from $table t where t.item_id = $table.item_id) DESC")
->get();
答案 1 :(得分:-3)
您可以在DB.raw中查询,例如:DB::select( DB::raw("SELECT p.name, part.* FROM programs p, parts part WHERE p.id = part.id"));