Laravel,更新多行数组
Posted
技术标签:
【中文标题】Laravel,更新多行数组【英文标题】:Laravel, Update Multiple rows Arrays 【发布时间】:2019-02-23 20:22:43 【问题描述】:我正在尝试使用数组更新多行数据。 也许我这样做的方式仍然有一些错误,所以这就是问题所在。
我有一个数据存储在数据库中,我将数据转换成一个数组,以便您更好地理解它。
array:4 [▼
0 => "I"
1 => "like"
2 => "your"
3 => "Mom"
]
当我尝试更新数据时*示例
array:4 [▼
0 => "I"
1 => "like"
2 => "your"
3 => "dad"
]
结果与我的预期不同。结果如下:
array:4 [▼
0 => "dad"
1 => "dad"
2 => "dad"
3 => "dad"
]
这里是我的控制器
public function updateTestCaseUser(Request $id)
$input = $id->all();
$x = TestCase::find($id["id"]);
$x->test_scenario = $input["test_scenario"];
$x->post_condition = $input["post_condition"];
$x->pre_condition = $input["pre_condition"];
$x->expected_result = $input["expected_result"];
// $x->steps = $input["steps"];
$x->actual_result = $input["actual_result"];
$x->status = $input["status"];
$x->save();
// Ignore these all ^
$hitung = $id->steps;
$hitung2 = count($hitung);
for ($i=0; $i < $hitung2; $i++)
$y = Steps::find($id["id"]);
$y->steps = $id->steps[$i]; // I am really sure the problem is at here
$y->save();
return redirect("/testing/user/document")->with('Alert-succes', 'Succesfull');
忽略 $hitung 的顶部。当我在 $hitung 上使用 dd() 时。结果和我预期的一样。像
array:4 [▼
0 => "I"
1 => "like"
2 => "your"
3 => "dad"
]
我的表格迁移步骤
public function up()
Schema::create('steps', function (Blueprint $table)
$table->increments('id');
$table->integer('id_steps')->unsigned()->index();
$table->foreign('id_steps')->references('id')->on('test_cases')->onDelete('cascade');
$table->integer('id_document');
$table->integer('id_test_case');
$table->text('steps');
$table->timestamps();
);
【问题讨论】:
您尝试在代码中的哪个位置更新这些数组? 查看控制器,查看$hitung to for 【参考方案1】:真的在这里猜测,但......也许......
$y->steps[$i] = $id->steps[$i];
编辑
在您的迁移中需要。
$table->json('steps');
在你的模型中添加
protected $casts = [
'steps' => 'array',
];
那你就可以写了
$y->steps = $id->steps
没有循环
【讨论】:
它不起作用,消息错误很像。间接修改重载属性 App\Steps::$steps 无效 老实说,我不确定你为什么要循环 $steps。你不能只使用 $y->steps = $id->steps 我已经尝试过这种方式,但它仍然出现错误消息。数组到字符串的转换(SQL:我尝试使用 implode,但结果是将我所有的输入数据变成一行 *examp Ilkeyyoudad 完成,请看我的问题 查看编辑。并检查laravel.com/docs/5.6/eloquent-mutators#array-and-json-casting以上是关于Laravel,更新多行数组的主要内容,如果未能解决你的问题,请参考以下文章