【问题标题】:Laravel query builder, having issue [duplicate]Laravel 查询生成器,有问题 [重复]
【发布时间】:2017-08-13 15:44:18
【问题描述】:

我有一个问题,不知道如何解决。 我需要从选择中获取特定对象,例如 { "iso":"UA", “故事”:122, “标题”:乌克兰 }

所以我有一个 sql 查询

SELECT
c.iso,
locale.title as title,
(SELECT COUNT(DISTINCT s.id) FROM stories AS s WHERE s.country_id = c.id) AS stories
FROM `countries` AS c
LEFT JOIN countries_locale AS c_l ON c.id=c_l.country_id
LEFT JOIN locales AS locale ON c_l.locale_id=locale.id
WHERE locale.locale = 'en'
GROUP BY c.id
HAVING stories>0

它工作正常,所以我尝试将此查询重写为 Laravel QB:

DB::table($this->getTable())
->select(
'countries.iso as iso',
'locales.title as title',
DB::raw('(SELECT COUNT(s.id) FROM stories AS s WHERE  s.country_id = countries.id) AS stories')
)
->leftJoin('countries_locale', 'countries.id', '=', 'countries_locale.country_id')
->leftJoin('locales', 'countries_locale.locale_id', '=', 'locales.id')
->where('locales.locale', \App::getLocale())
->groupBy('iso')
->having('stories', '>', 0)
->get();

然后我得到一个错误

语法错误或访问冲突:1055 'way.countries.id' 不在 GROUP BY 中

in 显示了一个 sql 字符串,我可以在 mysql 中成功执行

【问题讨论】:

标签: mysql database laravel having laravel-query-builder


【解决方案1】:

如果您希望 laravel 接受不是很严格的查询,请使用

'strict' => false

在数据库配置中。 或者,在您的情况下,您可以将这两列都放在 group by 的 select 中。

【讨论】:

  • 但我想要来自表格国家的所有列,为什么我需要放置所有这些列,如果我只想删除重复项?严格模式有效,谢谢!
猜你喜欢
  • 2018-11-16
  • 2019-03-29
  • 2021-08-11
  • 1970-01-01
  • 1970-01-01
  • 2018-06-26
  • 2015-08-06
  • 1970-01-01
  • 2021-01-10
相关资源
最近更新 更多