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

时间:2015-06-28 16:22:05

标签: php mysql laravel-4 laravel-excel

这是我的store方法,它抓取文件并循环遍历每一行:

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');
    }

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

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

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

    return false;
}

现在,当我仅导入6行时,似乎正在发生的事情实际上是插入到数据库中。

如果我在create方法中使用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都不是。 8(表中的下一个可用行)。表ID是defo AUTO INCREMENT等所以没有问题,我猜它是一个逻辑问题?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

好像你一遍又一遍地使用相同的模型实例。

尝试更改fill():

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

with create():

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

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

重要

使用 create()时,您也会将其持久保存到数据库中,这意味着您无需手动保存()