簡體   English   中英

在多對多關系中附加和分離

[英]Attach and detach In ManyToMany Relationship

我有一個 EmployeeSkill model 表是employee_skills 列是id、employee_id、skill_id

創建用戶時,我可以分配多個技能,並且我想為employee_skills 表中的特定用戶ID 分配所有技能ID。

我有員工和技能 model。

在兩個實體之間many to many關系中,我們有兩個模型和第三個表。 有關更多說明,請參閱文檔和laravel 文檔

你不需要EmployeeSkill model,刪除這個,根據laravel建議第三個表名最好是單數,按字母順序排列,像這樣: employee_skill

員工 model 關系:

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

技能 model 關系:

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

現在,當您想為特定員工分配所有技能 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