Laravel API-updateOrCreate

时间:2020-01-23 03:50:26

标签: laravel

我正在使用x y 12 a 13 a 14 b 15 c 存储动态字段中的数据。更新有效,但是添加新行时出现错误。

updateOrCreate

我尝试了这种方法,但是现在它既不能用于更新也不能用于创建。

public function store(Request $request) {
    foreach($request->rows as $row) {
      $db = Book::updateOrCreate(['id' => $row['id']]);
      $db->author_id = $request->author_id;
      $db->publisher_id = $request->publisher_id;
      $db->title = $row['title'];
      $db->genre = $row['genre'];
      $db->save();
    }
  }

错误消息 enter image description here enter image description here

3 个答案:

答案 0 :(得分:1)

updateOrCreate(数组$ attributes,数组$ values = [])

创建或更新与属性匹配的记录,并用值填充。

因此您的参数不正确。它需要两个数组参数,而不是一个数组。 检查一下:updateOrCreate

public function store(Request $request) {
    foreach($request->rows as $row) {
      $db = Book::updateOrCreate(
      ['id' => $row['id']],
      [
        'title' => $row['title']
      ]);
    }
  }

答案 1 :(得分:1)

更新或创建

您可能还会遇到想要更新 现有模型或如果不存在则创建一个新模型。 Laravel提供 一个updateOrCreate方法可一步完成。像 firstOrCreate方法,updateOrCreate持久化模型,因此没有 需要调用save():

updateOrCreate(数组$ attributes,数组$ values = [])

它应该是这样的。但是请确保您已填写模型

选项1

//Option 1
foreach($request->rows as $row) {
    $db = Book::updateOrCreate(
        [
            'id' => $row['id'] ?? null
        ],
        [
            'author_id' => $request->author_id,
            'publisher_id' => $request->publisher_id,
            'title' => $row['title'],
            'genre' => $row['genre']
        ]
    );
}

Options2

// Options 2
foreach($request->rows as $row) {
    $input = [
         'author_id' => $request->author_id,
         'publisher_id' => $request->publisher_id,
         'title' => $row['title'],
         'genre' => $row['genre']
    ];
    if (isset($row['id'])) {
        if($db = Book::find($row['id'])) {
            $db->update($input);
            continue;
        }
    }

    Book::create($input);
}

编辑:

错误表明您的路由不接受POST方法。.将其更改为POST方法

例如: Route::post()代替Route::get()

答案 2 :(得分:0)

确保在控制器中使用了模型

[('create_uid.team_id', '=', user.team_id.id)]

像这样在模型中编写受保护的可填充字段:

use App\ExampleModel;
相关问题