【问题标题】:How to get imported row id in Laravel Excel如何在 Laravel Excel 中获取导入的行 ID
【发布时间】:2020-05-15 01:20:25
【问题描述】:

我正在使用Laravel Excel,我需要在导入期间获取导入行的 ID。

代码

public function model(array $row)
{
    $link = new Link([
      'site_name'    => $row['site_name'],
    ]);

    $name = explode('-', $row['site_name']);
    $site = Site::whereIn('name', $name)->pluck('id');
    $link->sites()->sync($site, false);  // this `$link` can't get id of imported row

    return $link;
}

错误

SQLSTATE[23000]:违反完整性约束:1048 列“link_id” 不能为空(SQL:插入link_siteslink_idsite_id) 值 (?, 14))

有什么想法吗?

【问题讨论】:

  • 由于某种原因,您的link_id 为空
  • @PavloZhukov 是的,似乎$link 在行导入后不返回数据

标签: php laravel


【解决方案1】:

已解决

我已将我的函数更改为使用 onEachRow,它现在可以工作了。

public function onRow(Row $row)
{
    $rowIndex = $row->getIndex();
    $row = $row->toArray();
    
    $link = Link::create([
        'site_name'    => $row['site_name'],
    ]);

    $name = explode('-', $row['site_name']);
    $site = Site::whereIn('name', $name)->pluck('id');
    $link->sites()->sync($site, false);
}

Document

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 2016-06-01
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多