Reference in Related Tables | Laravel 5.4

1

I have the following relationship on a test system I'm doing.

:: MODEL EMPLOYEE

public function users(){
    return $this->hasMany('lbo\User');
}

:: MODEL USER

public function employees(){
    return $this->belongsTo('lbo\Employee');
}

In the users table I have employee_id . I need to recover employees who do not yet have created users.

What is the best way to get the consultation done?

    
asked by anonymous 05.07.2017 / 18:54

1 answer

0

With whereNotIn , and the employee_id field of the users table when unrelated, that is, NULL to work:

Example:

Employee::whereNotIn('id', function($q)
   { 
      $q->select('employee_id')
        ->from('users')
        ->whereRaw('not employee_id is null'); 
   })
   ->get();

With the user's comment, due to lack of information (unclear question) he was able to solve it with a ready method whereDoesntHave , example:

Employee::whereDoesntHave('users')->get();

It is worth remembering that many times the question is badly worded and this can be considered as unclear what happened .

The two solutions are feasible the first one for previous versions ( <=5.2 ) that does not have this method and the second one for the most current ones ( >=5.3 ).

06.07.2017 / 03:34