【问题标题】:Check if a Csv file contains column in Laravel?检查 Csv 文件是否包含 Laravel 中的列?
【发布时间】:2021-08-10 08:44:56
【问题描述】:

我正在使用Maatwebsite/Excel 导入文件并将数据存储在数据库中。

我想检查registered 列是否在文件中,否则为它创建一个新值。我在下面尝试了我的代码,但是当我检查我的数据库时,我看到created_at (timestamp) 列的日期是今天的日期,而不是 csv 文件列上的日期。

是因为迁移导致行没有更新吗?

因为我在User 迁移中有$table->timestamps();

class UsersImport implements ToModel, WithCustomCsvSettings, WithHeadingRow, WithUpserts
{
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function model(array $row)
    {
        return new User([
            'firstname' => $row['firstname'],
            'lastname' => $row['lastname'],
            'email' => $row['email'],
            'password' => $row['pass'],
            'created_at' => !empty($row['registered']) ? Carbon::parse($row['registered']) : Carbon::now(),
        ]);
    }

    public function getCsvSettings(): array
    {
        return [
            'delimiter' => ","
        ];
    }

    public function uniqueBy()
    {
        return 'email';
    }
}

【问题讨论】:

  • 你有什么错误吗?
  • @Pradeep 错误是当我检查我的数据库时,我看到created_at(时间戳)列的日期是今天的日期,而不是 csv 文件列上的日期。

标签: php laravel


【解决方案1】:

您的created_at 色谱柱质量是否可分配到您的User 型号中?我认为由于您使用的是mass assignment,您必须将您的created_at 列设置为可批量分配。您可以使用guardedfillable 属性来实现这一点。

您可以从 Laravel 文档中阅读更多内容:https://laravel.com/docs/8.x/eloquent#mass-assignment

【讨论】:

    【解决方案2】:

    我需要在我的模型中的$fillable 中添加created_at

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-30
      • 2021-10-30
      • 2012-10-11
      相关资源
      最近更新 更多