Vikram Singh
Vikram Singh

Reputation: 124

Php eloquent orm join multiple columns in a table to another table

Let's say I have a table Projects in which in a particular tuple I have many Users. For Example:

Projects

id    project_name    developer    manager    tester
1          w             ww           z          t
2          qq            y          ll         mm
...

Now, developer, manager and tester are user from the Users table. The project table contains the username of the user. Say the Users table is like

Users
    id    username    first_name    last_name    email_add
     1        ww         John         Smith       [email protected]
   ...

and I want to display the information about the project but I need the full name (first_name+" "+last_name) of all the users and not the username which is stored in the Projects table.

What would be an efficient way to approach this?

Upvotes: 0

Views: 184

Answers (1)

soredive
soredive

Reputation: 813

Use orm relation (see https://laravel.com/docs/5.7/eloquent-relationships#defining-relationships)

and accessor for full name. (see https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor)

For example In Project model

class Project extends Model {
.....
     # set relation
     public function developer() {
          return $this->hasOne('App\User', 'developer', 'username');
     }
     public function manager() {
          return $this->hasOne('App\User', 'manager', 'username');
     }
     public function tester() {
          return $this->hasOne('App\User', 'tester', 'username');
     }
.....
}

In User model

class User extends Authenticatable implements Member {
      .....
      # set relation
      public function project() {
           return $this->belongsTo('App\Project', 'user_id');
      }
      .....
      public function getFullNameAttribute(): string {
            if(!$this->cache_full_name) {
                 $this->cache_full_name = $this->first_name . ' ' . $this->last_name;
            }
            return $this->cache_full_name;
      }
      ......
 }

in use

$project = App\Project::query()->first();
echo $project->developer->full_name;
echo $project->manager->full_name;
echo $project->tester->full_name;

Upvotes: 1

Related Questions