Pass query from sql to laravel

0

I'm a bit new to Laravel, I have this query in sql and I want to move to laravel

Select users_groups.Name
FROM tm_employee
INNER JOIN users ON tm_employee.UserId = users.id
INNER JOIN users_groups ON users.groupId = users_groups.id
WHERE tm_employee.id = $variable

I am working with the models User, userGroup, employee

    
asked by gmrYaeL 24.10.2018 в 23:09
source

1 answer

0

To be able to make queries with Eloquent, it is necessary to define the relationships that exist between the models by adding methods in both classes. There are different types of relationships: "one to one", "one to many", "many to many", among others.

Learn more about relationships

The find method allows you to obtain a record based on your primary key. "Getting an instance of a model"

Select users_groups.Name
FROM tm_employee
WHERE tm_employee.id = $variable

is equivalent to

$user = App\User::find($userID);

Returns the user who has the indicated ID.

The with method allows you to obtain one or more relationships in a single operation. Receive a string with the name of the relation or an array of strings with the names of the relationships that interest you. Eager Loading

Select users_groups.Name
FROM tm_employee
INNER JOIN users ON tm_employee.UserId = users.id
INNER JOIN users_groups ON users.groupId = users_groups.id

is equivalent to

$users = App\User::with(['userGroup', 'employee'])->get();

Returns the full list of users including their group and their data as an employee.

Using both methods, it would be this way in the controller

$user = App\User::with(['userGroup', 'employee'])->find($userID);
    
answered by 24.10.2018 / 23:44
source