mercredi 31 octobre 2018

Query with circular relationship in Laravel 5.6

I have the following tables:

  1. Users;
  2. Companies;
  3. Employees.

I'm trying to bring all the employees of a company. In SQL it's pretty easy:

SELECT c.name, eu.name FROM users u
    JOIN companies c ON c.user_id = u.id
    JOIN employees e ON e.company_id = c.id
    JOIN users eu ON eu.id = e.user_id
 WHERE u.id = 2

But in Laravel I have tried everything and can not get this listing (company name + employee name) correctly.

Here are the frustrated attempts:

  1. In this I tried to get all the companies the user logged in to then list all the employees.

    $companies = Auth::user()->with('companies')->with('employee')->where('id', '=', Auth::user()->id)->get(); 
    
    
  2. Here I started with the Employee model.

    $employees = Employee::with('company')->with('user')->where('user_id', Auth::user()->id)->paginate(30); 
    
    

As the platform is multi user, it is interesting to remember that:

  1. A User has N Companies;
  2. A Company has N Employees;
  3. And an Employee belongs to ONE User.

Hence comes the circular structure of the tables.

enter image description here

Thank you.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2PCjmxe
via IFTTT

Aucun commentaire:

Enregistrer un commentaire