1

List item

I need to select data from a table whose id does not exits in another table or if exists then check other conditions. i can achieve this by

Task::join('events','events.task_id' ,'=','tasks.id')
        ->where('events.event_type','=','Task')
        ->where('events.task_stage','!=','assigned')->select('tasks.*');

but i don't think this is the right way.

For Example:

+-------------------------+   +-------------------------+
| tasks                   |   | Events                  |
+----------+--------------+   +-------------------------+
| id       |  name        |   | task_id  |  task_stage  |
| 1        |  Task1       |   | 1        |  'assigned'   |
| 2        |  Task2       |   | 2        |  'created'   |
+----------+--------------+    +----------+--------------+

Result Should be:

Task with id 2 which is only created not assigned. I am new to queries. Thanks in advance...

Priyanka khullar
  • 509
  • 1
  • 5
  • 25
Neha
  • 2,136
  • 5
  • 21
  • 50

1 Answers1

1

Pass a Closure as the second argument into the join method. The Closure will receive a JoinClause object which allows you to specify constraints on the join clause:

Task::join('events', function ($join) {
    $join->on('events.task_id', '=', 'tasks.id')
        ->where('events.event_type', '=', 'Task')
        ->where('events.task_stage', '!=', 'assigned');
})->select('tasks.*')->get();

Documentation

linktoahref
  • 7,812
  • 3
  • 29
  • 51