【发布时间】:2022-01-11 08:37:09
【问题描述】:
这很好用。
if ($request->link) {
foreach($request->name as $key => $social){
$stall->socials()->attach($social, ['value' => $request->link[$key] ?? null]);
}
}
但它不起作用。
if ($request->link) {
foreach($request->name as $key => $social){
$stall->socials()->sync($social, ['value' => $request->link[$key] ?? null]);
}
}
Stall.php
public function socials()
{
return $this->belongsToMany(Social::class)->withPivot('value');
}
问题是在更新过程中它根本不存储在数据库中。
【问题讨论】:
-
sync不是这样工作的……第一个参数是要保持同步的 id 列表……laravel.com/docs/7.x/…(“同步关联”小节)……它解释了如何与其他字段同步 -
如何用pivot保存?
-
它在文档中告诉您如何执行此操作,您必须以特定方式构建一个数组以传递给
sync的第一个参数 -
我将
sync替换为syncWithPivotValues,但出现错误Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::syncWithPivotValues() -
该方法在 Laravel 7.x 中不存在 ...您必须使用
sync...这对您也不起作用,因为您需要为每个 id 设置不同的枢轴值同步