Laravel 使用相同 ID 插入的 CSV 导入(简单导入)

Laravel CSV Import inserting with the same ID (Simple Import)

这是我的存储方法,它获取文件并遍历每一行:

public function store()
    {
        $input = Input::file('statuses');
        $filename = $input->getRealPath();
        $i = 0;

        $rows = Excel::load($filename, null, 'ISO-8859-1')->get()->toArray();

        foreach($rows as $k => $row)
        {
            if(!isset($err)) {
                if (!$this->repository->create($row))
                    $err = 'Error importing row ' + $i;
                    $i++;
                }
        }

        if(isset($err)) {
            Flash::error($err);
            return Redirect::route('admin.importstatus.index');
        }

        Flash::success('Statuses Imported!');
        return Redirect::route('admin.statuses.index');
    }

在我的存储库中,我的创建方法如下所示:

public function create(array $data)
{
    // Create the model
    $model = $this->model->fill($data);

    if ($model->save()) {
        return $model;
    }

    return false;
}

现在,当我仅导入 6 行时似乎发生了什么,最后实际上被插入到数据库中。

如果我 var_dump 在我的创建方法中,我将返回以下内容:

    array (size=7)
  'content' => string 'Imported two' (length=12)
  'status' => float 0
  'user_id' => float 1
  'pinned' => float 0
  'updated_at' => string '2015-06-28 16:13:22' (length=19)
  'created_at' => string '2015-06-28 16:13:22' (length=19)
  'id' => int 8
array (size=7)
  'content' => string 'Imported three' (length=14)
  'status' => float 0
  'user_id' => float 1
  'pinned' => float 0
  'updated_at' => string '2015-06-28 16:13:22' (length=19)
  'created_at' => string '2015-06-28 16:13:22' (length=19)
  'id' => int 8
array (size=7)
  'content' => string 'Imported four' (length=13)
  'status' => float 0
  'user_id' => float 1
  'pinned' => float 0
  'updated_at' => string '2015-06-28 16:13:22' (length=19)
  'created_at' => string '2015-06-28 16:13:22' (length=19)
  'id' => int 8

注意每个 ID 都是 no。 8(table 中的下一个可用行)。 tables ID 是 defo AUTO INCREMENT 等所以没有问题,我猜这是一个逻辑问题?有什么想法吗?

您似乎在一遍又一遍地使用同一个模型实例。

尝试更改 fill():

$this->model->fill($data);

使用 create():

$this->model->create($data);

使用 fill() 你只是用一些数据填充已经创建的模型实例。但是如果你使用 create() 你首先创建一个新的实例(有一个新的 id),然后用数据填充它然后保存它。

重要

当使用 create() 时,您还将它保存到数据库中,这意味着您不必 save()手动。