繁体   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