我在 user_id 和 product_id 上附加了一个额外的字段。在应该更新额外字段之前,一切都工作正常。当该字段将被第二次填充而不是更新时,它将向数据库添加另一个。这很明显,因为我使用的是附加而不是同步。但是当我使用 sync 时出现错误。
这是我的代码:
$price = $request->input('price');
$product = Product::find($id);
$product->users()->attach(Auth::id(), ['price' => $price]);
这是我在使用同步时遇到的错误:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::formatRecordsList() must be of the type array, integer given
最佳答案
sync()
方法的第一个参数应该是一个数组。所以正确的语法是:
$product->users()->sync([Auth::id() => ['price' => $price]]);
https://laravel.com/docs/5.4/eloquent-relationships#updating-many-to-many-relationships
关于php - Laravel 同步多对多错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44624252/