4

首先抱歉,我只在 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) ""
}

我尝试了其他几次尝试,但没有任何效果

请问有人可以帮我解决这个问题吗?

4

2 回答 2

1

在不了解更多有关向您传递请求对象的信息的情况下,我无法真正详细说明,但您可能希望让您的请求对象看起来像这样:

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

于 2017-02-03T17:39:02.760 回答
0

我认为,照片模型错过了可填充数组。

protected $fillable = ['var1', 'var2', ...];
于 2015-07-04T07:25:14.960 回答