SoyKrut
SoyKrut

Reputation: 103

convert query from mysql to php laravel?

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..

Upvotes: 0

Views: 73

Answers (3)

MD. Jubair Mizan
MD. Jubair Mizan

Reputation: 1560

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();

Upvotes: 0

Thijs
Thijs

Reputation: 1012

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).

Upvotes: 1

Pepe
Pepe

Reputation: 381

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();

Upvotes: 0

Related Questions