【问题标题】:Distinct in Laravel 5 not working properlyLaravel 5 中的 Distinct 无法正常工作
【发布时间】:2019-05-20 03:48:44
【问题描述】:

我想要数据库表中的不同名称。该表包含列 ID 和名称。

我试过了

$diff=Crud::distinct('name')->get();
$diff=Crud::distinct()->get();

他们都没有工作。他们返回的结果是重复的。这里 Crud 是我雄辩的模型。

但是当我使用时

$cnt=Crud::distinct()->count('name'); //returns the correct count

和

$u=Crud::all();
$diff=$u->unique('name'); //returns the distinct names

为什么在我使用 distinct 时会返回重复值?我想要使​​用 distinct 来区分名称。

谢谢。

【问题讨论】:

  • Crud 是你模型的名字吗?
  • 是的! Crud 是我的模型的名称。

标签: laravel-5 eloquent distinct


【解决方案1】:

distinct() 不接受参数。使用以下选项之一:

$diff = Crud::distinct()->pluck('name');

$diff = Crud::distinct()->get(['name']);

$diff = Crud::distinct()->select('name')->get();

【讨论】:

  • 正确。 distinct() 只是查询生成器中的一个标志。您仍然需要告诉数据库要区分什么。这就是->count('name'); 起作用的原因。而DB::all()->unique() 是一种收集方法。
猜你喜欢
  • 2015-12-03
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 2015-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多