簡體   English   中英

php雄辯的orm將一個表中的多個列連接到另一個表

[英]Php eloquent orm join multiple columns in a table to another table

假設我有一個表Projects,其中在一個特定的元組中,我有許多用戶。 例如:

Projects

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

現在,開發人員,經理和測試人員是Users表中的用戶。 項目表包含用戶的用戶名。 說用戶表就像

Users
    id    username    first_name    last_name    email_add
     1        ww         John         Smith       js@gmail.com
   ...

並且我想顯示有關該項目的信息,但是我需要所有用戶的全名(first_name +“” + last_name),而不是存儲在Projects表中的用戶名。

什么是解決此問題的有效方法?

使用orm關系(請參閱https://laravel.com/docs/5.7/eloquent-relationships#defining-relationships

和全名訪問者。 (請參閱https://laravel.com/docs/5.7/eloquent-mutators#defining-an-accessor

例如在項目模型中

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

在用戶模型中

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

正在使用

$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