0

This is my store method which grabs the file and loops through each of the rows:

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

In my repository, my create method looks like this:

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

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

    return false;
}

Now, what appears to be happening when I import 6 rows only the final is actually getting inserted into the DB.

If I var_dump in my create method, I am being returned the following:

    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

Notice how each of the ID's are all no. 8 (The next available row in the table). The tables ID is defo AUTO INCREMENT etc so no issues there, I guess its a logic issue? Any ideas?

4

1 回答 1

1

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

尝试更改填充():

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

使用创建():

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

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

重要的

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

于 2015-06-28T16:25:53.603 回答