简体   繁体   English

在多对多关系中附加和分离

[英]Attach and detach In ManyToMany Relationship

I have a EmployeeSkill model and table is employee_skills columns are id, employee_id, skill_id我有一个 EmployeeSkill model 表是employee_skills 列是id、employee_id、skill_id

When create user i can assign multiple skills and i want to assign all skills id for the specific user id in employee_skills table.创建用户时,我可以分配多个技能,并且我想为employee_skills 表中的特定用户ID 分配所有技能ID。

I have Employees and Skill model.我有员工和技能 model。

In many to many relationships between two entities, We have two models and a third table.在两个实体之间many to many关系中,我们有两个模型和第三个表。 for more explanation see this and laravel documentation .有关更多说明,请参阅文档和laravel 文档

you don't need the EmployeeSkill model, delete this, and accord to the laravel recommendation the third table name is better to be singular and in alphabetical order, like this: employee_skill .你不需要EmployeeSkill model,删除这个,根据laravel建议第三个表名最好是单数,按字母顺序排列,像这样: employee_skill

Employee model relation:员工 model 关系:

public function skills()
{
    return $this->belongsToMany(Skill::class);
}

Skil model relation:技能 model 关系:

public function employees()
{
    return $this->belongsToMany(Employee::class);
}

now when you wanna assign all skills id for a specific employee, you just need to attach or sync :现在,当您想为特定员工分配所有技能 ID 时,您只需要attachsync

$employee->skills()->sync({...you skills id...})

// -----

$employee->skills()->attach({...you skills id...})

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

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