Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel query. Where unique


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

Thanks in advance!

like image 314
Evaldas Butkus Avatar asked Jun 08 '15 12:06

Evaldas Butkus


2 Answers

You could use DISTINCT.

DB::table('table')->select('job_id')->distinct()->get();
like image 108
aebersold Avatar answered Oct 05 '22 23:10

aebersold


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'); });

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

like image 20
wiesson Avatar answered Oct 06 '22 01:10

wiesson