Reputation: 37
It's may be my question not clear to you but my English is weak. so suppose, I have two tables 'user' and 'project'. this project table contain two foreign keys from user table.
That's because, I want to indicate two people
(1) person who implement the project (Employee) (2) person who Mange or supervise the project (Manager)
user project -------------------- ----------------------------------------- user_id | name | |p_id | name | manager_id | employee_id | -------------------- ----------------------------------------- 001 | manager | p001 |ABC | 001 | 002 002 | employee |
you can see, project table refer user id as foreign key (manager_id and employee_id). because those two persons are users initially.
My question is, How can i get these users same time separately by using php laravel (Laravel Framework 5.5.45) when i am gonna show project details such as below?
Project ------------------------- project Name : ABC Manage By : manager Conduct By : employee -------------------------
I have found MySQL query but i haven't it right now to post here. i forgot to bookmark that stack overflow link.
Upvotes: 0
Views: 60
Reputation: 714
You should add
protected $table = 'project' because your table name like single. Laravel requred a single "s" whenever you create table like users,projects,services. in pivot table table name like user_role , role_permission etc.
class Project extends Model{
protected $table = 'project';
public function manager() {
return $this->belongsTo(User::class, 'manager_id');
}
public function employee(){
return $this->belongsTo(User::class, 'employee_id');
}
}
For Show at Blade file.
// Controller
public function index(){
$projects = Project::all();
return view('blade_File_Destination_Here',compact('projects'));
}
@foreach($projects as $project)
Project
-------------------------
Project Name : {{ $project->name }}
Manage By : {{ $project->manager->name }}
Conduct By : {{ $project->employee->name }}
-------------------------
@endforeach
Upvotes: 1
Reputation: 6233
You can use eloquent relationship for this. Use two relation in your Project Model like below:
class Project extends Model
{
public function manager()
{
return $this->belongsTo(User::class, 'manager_id');
}
public function employee()
{
return $this->belongsTo(User::class, 'employee_id');
}
}
So in view it will be something like
Project Name : {{ $project->name }}
Managed By : {{ $project->manager->name }}
Conduct By : {{ $project->employee->name }}
Check out Laravel Eloquent Relationship here
Upvotes: 2