簡體   English   中英

php laravel在需要連接的數據透視表上獲取數據

[英]php laravel get data on pivot table that needs joining

我正在設計一個具有這樣數據庫的系統

公司

id
name

雇員

id
name

公司職員

company_id
employee_id
employee_role

EmployeeRole

id
name

這是為了讓員工可以在許多公司中擔任不同的職務。 現在,查詢

App\\Company::find(1)->belongsToMany(Employee::class)->withPivot('employee_role')->get()

我可以得到像

App\Employee {#1183
         id: 7,
         name: "John Doe",
         avatar: null,
         salary: 20000,
         insurance: 4000,
         created_at: "2018-03-28 10:15:00",
         updated_at: "2018-04-06 03:56:48",
         user_id: null,
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#1172
           company_id: 1,
           employee_id: 7,
           employee_role: 3,


           },
       },

看一下pivot屬性,我可以在特定的公司中獲得他們的角色,但是我也需要角色名稱(例如'Manager'或'Sales')。 我想要類似的東西:

App\Employee {#1183
         id: 7,
         name: "John Doe",
         avatar: null,
         salary: 20000,
         insurance: 4000,
         created_at: "2018-03-28 10:15:00",
         updated_at: "2018-04-06 03:56:48",
         user_id: null,
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#1172
           company_id: 1,
           employee_id: 7,
           employee_role: 3,
**employee_role_name: "Manager"**
         },
       },

我如何使用Eloquent? 提前致謝

創建數據透視模型:

class YourPivotModel extends \Illuminate\Database\Eloquent\Relations\Pivot {
    public function role() {
        return $this->belongsTo(EmployeeRole::class, 'employee_role');
    }
}

像這樣使用它:

$c->belongsToMany(Employee::class)->withPivot('employee_role')
    ->using(YourPivotModel::class)->get();

然后,您可以像這樣訪問角色名稱:

$employee->pivot->role->name

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM