首先抱歉,我只用 php 开发了一个月,我不知道如何用 laravel 更新它
我想更新多张照片。
照片有标题说明等
我的问题是我不知道该怎么做。
我尝试了以下方法
public function update(Request $request, Photo $photo)
{
// loop through array of id's
foreach ($request->photo_id as $id)
{
// find
$photos = $photo->find($id);
// loop throug input fields
foreach ($request->except('_token', 'tags', 'photo_id') as $key => $value)
{
$photos->$key = $value;
$photos->save();
}
}
die();
}
出现以下错误
preg_replace(): Parameter mismatch, pattern is a string while replacement is an array
所以我发现问题出在值上
结果是这样的
关键变量
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
string(5) "title"
string(10) "country_id"
string(7) "city_id"
string(11) "category_id"
string(9) "cruise_id"
string(12) "itinerary_id"
string(4) "desc"
string(6) "people"
值变量结果
array(2) {
[0]=>
string(9) "title one"
[1]=>
string(9) "title two"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "1"
}
array(2) {
[0]=>
string(0) ""
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(1) "1"
[1]=>
string(0) ""
}
我尝试了几次其他尝试,但没有任何效果
有人可以帮我解决这个问题吗?
最佳答案
在不了解更多有关将请求对象传递给您的信息的情况下,我无法详细说明,但您可能希望让您的请求对象看起来像这样:
'photos' => [
{
'id' => 1,
'title' => 'title one',
// more properties ....
},
{
'id' => 2,
'title' => 'title two',
// more properties ....
},
]
然后尝试这样的事情:
public function update(Request $request)
{
// Loop through the request photo id's
$request->photos->each(function($photo) use ($request) {
// Return the photo object you want to update
$photo = Photo::find($photo->id);
// Get the things you want from the request and update the object
$photo->title= $request[$photo_id]->title;
// Save the object
$photo->save();
})
}
您可能还想尝试 dd();
函数而不是 die();
。它使调试变得更加容易。
关于php - 使用 Laravel 更新嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31097526/