Abishek
Abishek

Reputation: 11691

How can I formulate this query in Laravel 4

I have this MYSQL query and require to formulate this using Eloquent in Laravel4.

SELECT DISTINCT Employee.Name, Employee.Id FROM Employee
LEFT JOIN Team ON Employee.Id = Team.EmployeeId AND Team.TeamId = 1;
  1. How can I add an AND clause on the JOIN in Laravel.
  2. How can I add a DISTINCT to the SELECT in Laravel 4

Upvotes: 2

Views: 2151

Answers (1)

Muhammad Usman
Muhammad Usman

Reputation: 12503

Create your Employee model with convention or proper $table connection and then:

Employee::select(array(DB::raw('DISTINCT `Employee`.`Name`'), 'Employee.Id'))
    ->leftJoin('Team', function($join)
            {
                $join->on('Employee.id', '=', 'Team.EmployeeId')
                     ->on('Team.id', '=', DB::raw(1));
            })
    ->get();

If you want to use just Query Builder(Fluent) then replace Employee:: with DB::table('Employee')->.

Notes:

  • DB::raw() instructs Laravel not to put backtics there.
  • By passing a closure to join methods you can add more join conditions to it, on() will add AND condition and orOn() will add OR condition.

Upvotes: 8

Related Questions