【问题标题】:Laravel Many to many relationship with custom key relationLaravel 与自定义键关系的多对多关系
【发布时间】:2019-02-09 12:12:23
【问题描述】:

在将此问题标记为重复之前,请查看详细信息 :) 我有一个与自定义列链接的多对多关系相关的问题

我有以下表格

员工

 -Id
 -brink_id <----- This is third party id I am saving of employee
 -name

工作

-id
-brink_id <----- This is third party id I am saving of job
-description

员工工作

-id
-brink_id <----- This is third party id I am saving of relationship for third party
-brink_employee_id
-brink_job_id

在员工模型中我创建了关系

public function jobs()
{
    return $this->belongsToMany('App\Models\Job','employee_job','brink_employee_id','brink_job_id');
}

在乔布斯模型中

/**
 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
 */
public function employees()
{
    return $this->belongsToMany('App\Models\Employee','employee_job','brink_job_id','brink_employee_id');
}

实际上,我想与brink_id in employees tablebrink_id in jobs table 建立多对多关系,以brink_employee_id, brink_job_id in employee_job 表而不是ID(各个表的主列)。

但是当我尝试使用以下方法插入数据透视表时,它总是插入员工 ID 而不是 brink_id

  $employee = Employee::with('jobs')->where('brink_id',$employeeJob['brink_employee_id'])->first();

  $employee->jobs()->attach($employeeJob['brink_job_id'], ['is_active' => 1]);

例如如果employee表中的brink_id为123456,ID为1,则上面的employee_table中的代码将在employee_brink_id中存储1而不是123456。

请让我知道我做错了什么。

【问题讨论】:

  • 你的 Laravel 版本是什么?
  • @JonasStaudenmeir 这是 5.2
  • 自定义本地键仅在 Laravel 5.5+ 中支持。

标签: laravel eloquent many-to-many


【解决方案1】:

如果您不指定不同的父键和相关键,它将分别默认为您当前模型的主键和相关模型的主键。

指定父键名作为第 5 个参数,相关键名作为第 6 个参数:

return $this->belongsToMany('App\Models\Employee', 'employee_job', 'brink_job_id', 'brink_employee_id', 'brink_id', 'brink_id');

但是,我个人会在您的关系中使用来自您系统的 ID,而不是来自第 3 方系统的 ID。

【讨论】:

  • 已按要求更改,但仍未保存 employee_brink_id。它仍在保存其 ID。但它实际上是在保存边缘工作 ID。 return $this-&gt;belongsToMany('App\Models\Job','employee_job','brink_employee_id','brink_job_id', 'brink_id', 'brink_id');
  • 所以 brink_job_id 匹配但不匹配 brink_employee_id?您如何同步记录?
  • 我实际上正在使用attach。找到员工$employee = Employee::with('jobs')-&gt;where('brink_id',$employeeJob['brink_employee_id'])-&gt;first(); 然后attachig as $employee->jobs()->attach($employeeJob['brink_job_id'], ['is_active' => 1]);
  • 不要使用 brink_job_id 附加,附加模型实例或使用模型的主键。
  • 没有得到Don't attach using the job id, attach the model instance。您能否解释一下,因为作业 ID 实际上是正确保存的。但不是员工 ID
猜你喜欢
  • 2021-04-04
  • 1970-01-01
  • 2018-03-16
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
  • 2017-06-21
  • 2015-07-20
相关资源
最近更新 更多