这是我的代码:
$qb = $this->_em
->createQueryBuilder();
$query = $qb->select('COUNT(food) as cnt')
->from(Food::class, 'food')
->groupBy('cnt')
->getQuery()->getSQL();
但是我的期望类似于以下查询:
SELECT COUNT(f0_.food_id) AS sclr_0 FROM foods f0_ WHERE (f0_.deleted_at IS NULL) GROUP BY sclr_0
结果如下:
SELECT COUNT(f0_.food_id) AS sclr_0 FROM foods f0_ WHERE (f0_.deleted_at IS NULL) GROUP BY f0_.food_id
有什么建议吗?
答案 0 :(得分:0)
在此处查看重定向: Laravel Group By Count Multiple Columns
$products_data = DB::table("products")
->select("products.id", "products.name", DB::raw("COUNT(click.*) as count_click"))
->join("click","click.product_id","=","products.id")
->groupBy("products.id")
->get();
print_r($products_data);
也尝试此代码
$this->select(\DB::raw("*, count(*) as total"))
->where('viewed', "0")
->groupBy(["chat_id", "type"]);
答案 1 :(得分:0)
您将需要将查询用作子查询,请在原始SQL中执行此操作,但是您可以从以下方法中获得灵感:
$qb = $this->_em
->createQueryBuilder();
$query = $qb->select('COUNT(food) as cnt')
->from(Food::class, 'food')
->groupBy('cnt')
->getQuery()->getSQL();
$qb2 = $this->_em
->createQueryBuilder();
$query2 = $qb->select('sclr_0')
->from('('.$query.')', 'cnt')
->groupBy('sclr_0 ')
->getQuery()->getSQL();