php – 使用Laravel更新嵌套数组

前端之家收集整理的这篇文章主要介绍了php – 使用Laravel更新嵌套数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
首先抱歉,我只在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',]

然后尝试这样的事情:

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();.它使调试变得更容易.

猜你在找的Laravel相关文章