【问题标题】:Laravel. Postgres. The date is not written from the array to the database拉拉维尔。邮递员。日期未从数组写入数据库
【发布时间】:2020-08-14 15:39:14
【问题描述】:

我得到的错误: SQLSTATE [23502]:非空违规:7 错误:“update_date”列中的空值违反非空约束详细信息:失败行包含(1,美元,27.4083,空,t,空,空)。 (SQL: 插入 "uan_rates" ("ratio", "to") 值 (27.4083, USD))

  1. 我的模特:

类 UanRate 扩展模型 {

protected $dateFormat = 'Y-m-d';
protected $table = 'uan_rates';
protected $casts = [
    'update_date' => 'date:Y-m-d',
];

public static function  getData() {

    $guzzle = Guzzle::getRemoteDate();

    //Iterating over the JSON array received from the API
    foreach ( $guzzle as $value ) {
        foreach ( $value as $item ) {
            $to = $item['cc'];
            $ratio = $item['rate'];
            $update_date = $item['exchangedate'];
            $d = date( 'Y-m-d', strtotime( $update_date ) );
            $update = true;

            $checkDate = date( 'Y-m-d' );
            if ( $checkDate != $d ) $update = false;

            //Database entry
            \DB::table( 'uan_rates' )
            ->updateOrInsert(
                ['ratio' => $ratio],
                ['to' => $to],
                ['update' => $update],
                ['update_date' => $d]
            );

            continue;

        }

        continue;

    }

}

}

2.我的迁移

public function up()
{
    Schema::create('uan_rates', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('to')->nullable();
        $table->float('ratio');
        $table->date('update_date');
        $table->boolean('update')->default(true);
        $table->timestamps();
    });
}

【问题讨论】:

  • 它唯一的插入"ratio", "to",但不是'update', 'update_date',您使用的是查询生成器而不是模型。所以这里不需要 fillable 方法。有趣的问题。您正在使用UpdateOrInsert,但这里没有条件,因此请尝试仅使用Insert 方法
  • 它给出了同样的错误,只是现在数据没有写入“to”

标签: php laravel


【解决方案1】:

您以错误的方式使用updateOrInsert ...

updateOrInsert(array $attributes, array $values = [])

updateOrInsert 方法将首先尝试使用第一个参数的列和值对来定位匹配的数据库记录。如果记录存在,它将使用第二个参数中的值进行更新。如果找不到记录,将插入一条新记录,其中包含两个参数的合并属性

 \DB::table('uan_rates')
            ->updateOrInsert(
                ['ratio' => $ratio,'to' => $to],
                ['update' => $update,'update_date' => $d]);

所以.. 如果您的表 (uan_rates) 中的任何记录与 ('ratio' 和 'to') 列匹配,它将被更新为新值 ('update' 和 'update_date') 否则,新行将被创造...

【讨论】:

    猜你喜欢
    • 2023-01-05
    • 1970-01-01
    • 2017-04-28
    • 2017-03-12
    • 2020-03-26
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-12
    相关资源
    最近更新 更多