Laravel 查询。独一无二的地方

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30709144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:44:05  来源:igfitidea点击:

Laravel query. Where unique

phpsqllaraveleloquent

提问by Evaldas Butkus


I got database table like this:


我得到了这样的数据库表:

**job_id**
    5
    5
    5
    6
    6
    7
    8
    8

I want to write query, which could select only unique id's. By saying unique I mean select only these values once:
5, 6, 7, 8

我想编写查询,它只能选择唯一的 id。说独特是指只选择一次这些值:
5, 6, 7, 8

Thanks in advance!

提前致谢!

回答by aebersold

You could use DISTINCT.

您可以使用DISTINCT

DB::table('table')->select('job_id')->distinct()->get();

回答by wiesson

How about:

怎么样:

$jobs = DB::table('my_job_table')
    ->groupBy('job_id')
    ->get();

Eloquent:

雄辩:

  1. First, you need a model. You could generate this by using php artisan. php artisan make:model jobs(I assume you have done this already) This will create a model in /your_project/app/Job.php
  2. Now you can use Eloquent (here in a route, to see some output):

    Route::get('/jobs', function () { $jobs = \App\Job::groupBy('job_id')->get(); return $jobs->lists('job_id'); });

  1. 首先,你需要一个模型。您可以使用 php artisan 生成它。php artisan make:model jobs(我假设你已经这样做了)这将在 /your_project/app/Job.php 中创建一个模型
  2. 现在你可以使用 Eloquent(这里在一个路由中,查看一些输出):

    Route::get('/jobs', function () { $jobs = \App\Job::groupBy('job_id')->get(); return $jobs->lists('job_id'); });

will return something like: [0,1,3,4]instead of [0, 1, 1, 1, 3, 4, 4, 4].

将返回类似:[0,1,3,4]而不是[0, 1, 1, 1, 3, 4, 4, 4].