所以我试图遍历对象数组以使用对象中的值更新数据库中的某些值
当我在控制器中运行此循环
foreach($statuses as $status){
$workflow->statuses()->where('id', $status->id)->update([
'status' => $status->status
]);
};
它给我错误trying to get property of non-object
当我执行`return response($ request-> statuses)时,这是我在控制台中看到的数据结构
这是完整的控制器
public function workflowStatuses(Request $request, Workflow $workflow)
{
// validate form data
$data = $request->validate([
'workflow' => 'required|string',
]);
// validate form data
$oldStatuses = $request->validate([
'statuses' => 'required|array'
]);
// validate form data
$newStatuses = $request->validate([
'newStatuses' => 'required|array',
]);
$workflow->update($data);
$statuses = $oldStatuses;
foreach($statuses as $status){
$workflow->statuses()->where('id', $status['id'])->update([
'status' => $status->status
]);
};
$workflow->statuses()->saveMany($newStatuses);
return response($workflow, 200);
}
答案 0 :(得分:1)
您可以将$request->validate()
的返回值视为所有请求输入的数组,将其过滤为仅包含正在验证的数据。如果该经过验证的数据包含数组,那么您将拥有一个多维数组。
在这里,$oldStatuses
将是一个包含名为statuses
的键的数组,该键包含您要查找的实际数组。
$oldStatuses = $request->validate([
'statuses' => 'required|array'
]);
// $statuses should get 'statuses' out of this validated array
$statuses = $oldStatuses['statuses'];
相反,您可能需要清理它,而不要三次调用validate。通常最好在一次validate()调用中运行所有验证规则,除非您有充分的理由将它们逻辑上分开。
$validated = $request->validate([
'workflow' => 'required|string',
'statuses' => 'required|array',
'newStatuses' => 'required|array',
]);
$statuses = $validated['statuses'];
答案 1 :(得分:0)
尝试:
foreach($statuses as $status){
$workflow->statuses()->where('id', $status['id'])->update([
'status' => $status['status'] //$status['status'] should also be accessed by key
]);
};