Laravel 5.3,我有两个模型:
用户:
public function newFunctions()
{
return $this
->belongsToMany('App\NewFunctions', 'user_newfunctions')
->withPivot(['function_count', 'days_count']);
}
NewFunctions
public function users()
{
return $this
->belongsToMany('App\User', 'user_newfunctions', 'new_function_id', 'user_id')
->withPivot(['function_count', 'days_count']);
}
现在,我该如何使用以下方法将新数据保存到用户:
$user = User::findOrFail($id);
$user->name = $request->input('name');
$user->save();
但是现在我必须更新数据透视表的某些值。数据透视表是这样的:
user_id | new_functions_id | function_count | days_count
---------------------------------------------------------
814 | 1 | 5 |2019-07-19 12:26:19
814 | 3 | 7 |2019-07-19 12:26:19
每个user_id
的行数超过1。我正在尝试使用:
$user
->newFunctions()
->sync([
'days_count' => $test_date,
'function_count' => $test_int_number
]);
但是我遇到类似这样的错误
非法偏移类型
因为正在尝试更新:
array(
'records' => array(
'days_count' => object(Carbon), 'function_count' => '66'),
'results' => array(),
'id' => object(Carbon),
'attributes' => array()
)
)
in BelongsToMany.php
所以:
sync
仅更新“ function_count”和“ days_count”?它们来自请求。答案 0 :(得分:1)
->sync()
不是那样使用的;它用于attach()
和detach()
相关的new_function_ids
,直到ids
中只有sync()
。您可能正在寻找updateExistingPivot()
->sync()
的示例将使用数组:
$user->newFunctions()->sync([
"new_function_id" => 1,
"function_count" => 6,
"days_count" => "2019-07-08 12:00:00",
]);
这将删除new_function_id
为3
的记录,并更新new_function_id
为1
的值。
要为function_count
或days_count
中的new_function_id
更新1
和3
,请使用->updateExistingPivot()
(通过id
您要更新为第一个参数):
$user
->newFunctions()
->updateExistingPivot("1", [
"function_count" => 6,
"days_count" = "2019-07-08 12:00:00"
]);
// or $user->newFunctions()->updateExistingPivot("3", ...);
这将更新new_function_id
为1
的数据透视表,同时保留new_function_id
为3
的行。
编辑:如果要更新数据透视表中的所有现有记录,则需要循环执行此操作,在单个数组中调用与所有当前记录的同步,或运行手动查询。 / p>