简体   繁体   English

php雄辩的orm将一个表中的多个列连接到另一个表

[英]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. 假设我有一个表Projects,其中在一个特定的元组中,我有许多用户。 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. 现在,开发人员,经理和测试人员是Users表中的用户。 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       js@gmail.com
   ...

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. 并且我想显示有关该项目的信息,但是我需要所有用户的全名(first_name +“” + last_name),而不是存储在Projects表中的用户名。

What would be an efficient way to approach this? 什么是解决此问题的有效方法?

Use orm relation (see https://laravel.com/docs/5.7/eloquent-relationships#defining-relationships ) 使用orm关系(请参阅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 ) (请参阅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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM