将Laravel 5.2与宅基地一起使用。我有以下模型:Dar,Activity,Destination和User。我有相应的控制器名称和一个reportsController。在Tinker,我写道:
$activityByName = DB::table('dars')->select('activity_id',DB::raw('count(*) as total'))->groupBy('activity_id')->get();
=> [
{#763
+"activity_id": 1,
+"total": 2,
},
{#764
+"activity_id": 3,
+"total": 1,
},
{#754
+"activity_id": 4,
+"total": 1,
},
]
太棒了,但是当我把它放在我的ReportsController中时:
$activityByName = Dar::with('activity')->select('activity_id')- >raw('count(*) as total')->groupBy('activity_id')->get();
返回:
驾驶:3 飞行:3 划船:3
我想看到的是:
驾驶:2 飞行:1 划船:1
“with('activity')”用于显示活动名称而不是值(例如,驾驶而不是activity_id:1)。我感谢任何帮助。
答案 0 :(得分:0)
只需使用" withCount "方法:
$activityByName=Dar:withCount('activity')->get();
foreach ($dar as $activityByName)
echo $dar->activity_id . ': ' . $dar->activity_count;
&#34; withCount &#34;方法生成一个新的字段&#39;名为 <related_tablename>_count
。
见https://laravel.com/docs/5.2/eloquent-relationships#querying-relations
(向下滚动到&#34;计算关系结果&#34;)