【问题标题】:Laravel 5.3 distinct count, using eloquent instead of Query BuilderLaravel 5.3 distinct count,使用 eloquent 而不是 Query Builder
【发布时间】:2017-04-23 18:48:49
【问题描述】:

遇到一个奇怪的问题,我最初尝试过的地方

$usersWithAnswersCount = GameResult::where([
    'school_id' => null,
    'season_id' => $this->season->id
])
->groupBy('user_id')
->count();

我的桌子看起来像

但是,当它本应返回 "2" 时,我得到了结果 "1"

当我检查运行的查询是 select count(*) as aggregate from game_results where (school_id is null and season_id = '1') group by user_id - 如果我直接作为 mysql 查询运行返回 2!!

所以看起来 eloquent 中的某些东西正在将我的 2 更改为 1 :(

但是,如果我将其更改为 DB Query Builder 并写出

$usersWithAnswersCount = DB::table('game_results')
->selectRaw('count(distinct user_id) as count')
->where([
    'school_id' => null,
    'season_id' => $this->season->id
])
->first()->count;

我回复"2",这是我的预期。

但是我不清楚为什么 Eloquent 方法会失败,如果可能的话我可以做些什么来修复它。

【问题讨论】:

  • 你是如何输出这些结果的?
  • 混合使用dump($usersWithAnswersCount);dd($usersWithAnswersCount);

标签: php mysql laravel count eloquent


【解决方案1】:

您可以使用 Laravel 的 distinct() 方法从数据库中获取不同的记录。

更新

你可以试试这个:

$usersWithAnswersCount = GameResult::where([
    'school_id' => null,
    'season_id' => $this->season->id
])
->distinct('user_id')
->count();

希望这会有所帮助!

【讨论】:

  • 第一个不同的作品,我相信@anwerjunaid 发布了同样的作品
  • 是的,那是我的错,我已经更新了代码,如果你投了反对票,你可以撤消它,因为现在我的回答是有效的:D
  • PlusOne 表示第一个不同,第二个仍有缺陷。
  • distinct() 查询生成器函数不接受任何参数...这不起作用。您想将列放在count() 函数中,即->distinct()->count('user_id');
【解决方案2】:

您所做的查询对于用例不正确,您可以看到差异。

select count(*) as aggregate from game_results 
where (school_id is null and season_id = '1') 
group by user_id order by user_id asc;

将返回两行

aggregate
1,
2

Eloquent 先选,然后返回 1。

select count(*) as aggregate from game_results 
where (school_id is null and season_id = '1') 
group by user_id order by user_id desc;

将返回行为

agrregate
2,
1

Eloquent 在这种情况下会产生 2。

您想要的是(查询)计数,这将再次为 2。

明白了吗?你想要的是DISTINCT

$usersWithAnswersCount = GameResult::where([
    'school_id' => null,
    'season_id' => $this->season->id 
])
->distinct('user_id')
->count();

【讨论】:

  • 好吧,我发誓我们试过了!!但是是的,有效:D
猜你喜欢
  • 2023-03-29
  • 2016-12-21
  • 1970-01-01
  • 2019-08-11
  • 2015-06-15
  • 2018-03-12
  • 2020-04-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多