现在,我有一个子查询来获取当月的付款计数,然后获得具有最高payment_count的4个产品。这个查询运行得很好,但我想知道是否有更简单的方法来做同样的事情,因为它变得难以阅读。
$latestPayments = DB::table('payments')
->select('product_id', DB::raw('COUNT(*) as payments_count'))
->whereMonth('created_at', Carbon::now()->month)
->groupBy('product_id');
$trendingProducts = DB::table('products')
->joinSub($latestPayments, 'latest_payments', function ($join) {
$join->on('products.id', '=', 'latest_payments.product_id');
})->orderBy('payments_count', 'DESC')->take(4)->get();发布于 2020-08-24 10:21:04
这就是它!
$trendingProducts = Product::withCount(['payments' => function($query) {
$query->whereMonth('created_at', Carbon::now()->month);
}])->orderBy('payments_count', 'DESC')->take(4)->get(); 发布于 2020-08-24 08:39:38
如果您正在关系数据库中使用eloquent query,您可以这样做:
$latestPaymentWithTrendingProduct = App\Payment::with(['products', function($product) {
$product->orderBy('payments_count', 'DESC')->take(4);
}])->whereMonth('created_at', date('m'))->get()->groupBy('product_id');这将减少代码,但仍然会做同样的事情。
https://stackoverflow.com/questions/63552998
复制相似问题