user3152250
user3152250

Reputation: 37

How to get data from single table with two forigin keys from that table in laravel

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

Answers (2)

Ripon Uddin
Ripon Uddin

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'));
}

View Process at Blade File

@foreach($projects as $project)
   Project
   -------------------------
   Project Name : {{ $project->name }}
   Manage By : {{ $project->manager->name }}
   Conduct By : {{ $project->employee->name }}
   -------------------------

@endforeach

Hope so it will be work for you

Thank you

Upvotes: 1

zahid hasan emon
zahid hasan emon

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

Related Questions