【发布时间】:2018-08-11 23:49:39
【问题描述】:
我几乎在每一个到数据透视表的 sync() 上都处理过这个问题,在 Laravel 5.6 中,当我执行以下操作时,它会添加请求中不存在的一行:
$firm_data = request()->all(); // get the request data
$firm = Firm::where('id', request('firm_id')); // get the Firm model
$firm->update($firm_data); // update the model
// add the firm address with a belongsToMany() relationship set on Models\Firm and on Models\Address
$address = $firm->with('addresses')->first();
$addresses = request('addresses'); // get the request data for address
$address->update($addresses); // all ok till here
// deal with the pivot table
// here's the issue...
$address->cities()->sync([request('firm_id'), $addresses['city_id']]);
公司数据和地址数据状态已正确保存在数据库中,尽管数据透视表填充了两列而不是一列。
在整个请求中,我只有一个city_id = 3034856,但将它添加到数据透视表的第一行firm_id = 1,city_id = 1,“不知从何而来”:
数据透视表 - Firm_city
+---------+---------+
| firm_id | city_id |
+---------+---------+
| 1 | 1 |
| 1 | 3034856 |
+---------+---------+
对为什么会发生这种情况有任何想法吗?
只是为了确保它是正确的,这里是每个模型公司和地址的方法:
// On the Firm model
public function cities()
{
return $this->belongsToMany(City::class, 'firm_city');
}
// on the City model
public function firms()
{
$this->belongsToMany(Firm::class, 'firm_city');
}
提前感谢您对为什么会发生这种情况的任何见解,
【问题讨论】:
标签: laravel eloquent many-to-many pivot-table