gpt4 book ai didi

php - Laravel CSV 导入插入相同 ID(简单导入)

转载 作者:行者123 更新时间:2023-11-29 12:08:21 25 4
gpt4 key购买 nike

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

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(表中的下一个可用行)。表 ID 是 defo AUTO INCREMENT 等,所以没有问题,我猜这是一个逻辑问题?有什么想法吗?

最佳答案

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

尝试更改 fill():

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

使用create():

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

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

重要

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

关于php - Laravel CSV 导入插入相同 ID(简单导入),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31102019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com