0

My query is the following:

select employe.id, employe.nam, users.name, users.name_user from employe left join users on users.name = employe.id

it is a query to two tables: employe, users.

How can I pass it to my controller? Am I new to laravel..

3 Answers 3

1

I assume the user to employee is a One to One relation. Did you setup the relation in both models?

If so you can do the following in your controller:

$employees = Employee::with('user')->all();

This will load all employees and the related user. Question is the users.name a foreign key on the employee.id? Thats a bit strange, i recommend using id's on both models (autoIncrement).

Sign up to request clarification or add additional context in comments.

Comments

0

Laravel use a MVC pattern, a good practice is use a Model for your employe table

I recomend you to use an Eloquen Model, so, your query will look like this:

Employe::select('employe.id', 'employe.nam', 'users.name', 'users.name_user')
       ->leftJoin('users', 'users.name', 'employes.id')
       ->get();

2 Comments

Your table is named 'employe', then your model needs a table name override, you need to pass the protected $table = 'employe';.
And what will be returned? Employe model with a mix of related and unrelated attributes. I'd rather have std class returned in this case than a twisted Eloquent model.
0

You can easily maintain this kind of query with Eloquent relationships.

Add this method on your employee model

public function user(){
   return $this->hasOne('App\User','name','id');
}

Add this method on your user model

public function Employee(){
   return $this->belongsTo('App\Employee','id','name');
}

Add line on your controller

$employees = Employee::with('user')->all();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.