基于Laravel文档的原始查询,我能够获得一个选择字段的计数,以便在产品模型中使用此代码。
public function scopeShowProductCount($query)
{
$query->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))
->groupBy('pid')
->orderBy('count_pid', 'desc');
}
该外观在控制器中获得了相同的结果:
$products = DB::table('products')->select(DB::raw('DISTINCT pid, COUNT(*) AS count_pid'))->groupBy('pid')->orderBy('count_pid', 'desc')->get();
这两个查询的结果转储如下:
#attributes: array:2 [
"pid" => "1271"
"count_pid" => 19
],
#attributes: array:2 [
"pid" => "1273"
"count_pid" => 12
],
#attributes: array:2 [
"pid" => "1275"
"count_pid" => 7
]
pid
列,所以如果你有你的表2的记录-一个用PID 1,第二位PID 2,计数应返回2