我使用Laravel 5.8,我想在统计表中计算平均观看次数。
统计信息表的列为post_id。
我想通过此操作计算平均观看次数:
用户观看次数/所有观看次数=观看次数平均值
$totalViews = Statistic::whereHas('post', function ($query) use ($user) {
$query->where('posts.user_id', $user->id);
})->where('created_at', '>=', Carbon::now()->subYear(1))->count();
$globalViews = Statistic::where('created_at', '>=', Carbon::now()->subYear(1))->count();
$rate = round($totalViews / $globalViews * 100, 0);
我只想查询,因为我想根据自己的要求下订单。
SELECT users.first_name, ROUND(COUNT(statistics.id) / (
SELECT COUNT(*)
FROM statistics) * 100, 2) AS average
FROM users
LEFT JOIN posts ON users.id = posts.user_id
LEFT JOIN statistics ON posts.id = statistics.post_id
GROUP BY users.id;
$users = DB::table('users')
->select('users.first_name', DB::raw('ROUND(COUNT(statistics.id) / (SELECT COUNT(*) FROM statistics) * 100, 2) AS average'))
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->leftJoin('statistics', 'posts.id', '=', 'statistics.post_id')
->groupBy('users.id')
->get();
是否可以通过雄辩的水合作用?