我想在laravel中显示此查询:
SELECT products.*, (
SELECT COUNT(*)
FROM category
WHERE category.product_id = products.id
AND category.date_creation BETWEEN '2018-02-16 00:00:00' AND '2018-02-19 23:59:59'
GROUP BY product_id
)nbr
FROM products
我试着用这个:
$a= $date_du;
$b = $date_au;
$products = DB::table('products')
->leftjoin('category','category.product_id','=','products.id')
->select('products.*',
DB::raw("(SELECT COUNT(*) FROM category
WHERE category.product_id = products.id AND category.date_creation >= '$a' AND category.date_creation <= '$b' group by product_id) as nbr"))
->get();
但是分组的条款不起作用。
答案 0 :(得分:1)
试试这个,
$products = DB::table('products')
->leftjoin('category','category.product_id','=','products.id')
->whereBetween('date_creation',[$a,$b])
->select(DB::raw('COUNT(*) as nbr'), 'products.*')
->groupBy('id')
->get();
这可能适合你。
答案 1 :(得分:0)
你也可以这样做:
$products=DB::select("SELECT products.*, ( SELECT COUNT(*) FROM category WHERE category.product_id = products.id AND category.date_creation BETWEEN '2018-02-16 00:00:00' AND '2018-02-19 23:59:59' GROUP BY product_id )nbr FROM products" );
这将运行原始查询并返回所需的输出。