Consultation in Related Tables | Laravel 5.4

Asked

Viewed 455 times

1

I have the following relationship in a test system that I’m doing.

:: MODEL EMPLOYEE

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

:: MODEL USER

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

On the table users have the employee_id. I need to recover the employees (Employee) who do not yet have users (user) created.

How best to consult?

  • Put the whole Model in question not only the relationship! and also failed to tell if the field of the relation which is the default value when it has no relation, which is usually left to receive value null, but, failed to say it. Even missing some thing I decided to post a solution

  • Thanks for the return Virgilio. Really the question was incomplete. As a business rule I can only create a user for an existing employee, this assures me that I will never have an employee_id in the users table with the NULL value. Reading the documentation I found this condition $Employees = Employee::whereDoesntHave('users')->get(); which met me well.

  • Next, I edited my answer, made the solution for the versions of Laravel and if it is useful consider as answer to your question. It is good to credit the answers of those who are helping you and this is the basis for community, thank you.

1 answer

0


With whereNotIn, and the countryside employee_id table users when it has no relationship, that is to say, 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 the lack of information (unclear question) he managed to solve also with a ready method whereDoesnHave, example:

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

and it is worth remembering that often the question is poorly formulated and this can be considered as not clear that was what happened.

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

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.