我一直在对透视表的每个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');
}
预先感谢您对为什么会发生这种情况的任何见识,
答案 0 :(得分:4)
删除firm_id
:
$address->cities()->sync([$addresses['city_id']]);
口才是从firm_id
获取$address
的,您不必指定它。
如果指定
Eloquent假设您要与City
同步id=1
。