【问题标题】:Laravel insert empty value Postgress errorLaravel插入空值Postgres错误
【发布时间】:2014-05-05 03:34:10
【问题描述】:

在 Laravel 4 中使用 ORM 创建元素时:

FigureModel::create( array( 'numericFieldOne'=>1, 'numericFieldTwo'=> null ) );
FigureModel::create( array( 'numericFieldOne'=>1, 'numericFieldTwo'=> '' ) );

在mysql中一切都很好,所有的项目都是完美的插入器,到目前为止没有问题:

但在 postgress 中,它会尝试插入空值而不带引号,从而导致 postress 崩溃。像这样:

怎么办??有谁知道如何解决这个问题?谢谢!!

(每个元素的自定义设置器将其验证为数字或 null 不是一个选项)

【问题讨论】:

  • 亲爱的理查德,很抱歉我的截图冒犯了你,从现在开始就按照你的建议去做。但是期望我试图让每个人的生活变得更加艰难,你不觉得有点牵强!

标签: postgresql orm pdo laravel insert


【解决方案1】:

@pozs 谢谢!既然你指出正确的错误应该是 42601 我再次确信这个 orm 的 prostgress 适配器是健全的。

解决办法: 在我的情况下,我只需要为数据库中的所有数字空值创建 setter 函数,就像这样

public function setNumericFieldAttribute($var){
    $this->attributes['numericField'] = empty($var) ? null : $var;
}

这样值总是空值或者值

谢谢!!

【讨论】:

    【解决方案2】:

    似乎 Laravel 的调试屏幕欺骗了你:如果查询真的是这样,那么 postgres 错误将是 syntax error at or near "," with SQL state 42601

    问题是,postgres 不接受 ''(空字符串)作为整数的有效表示。

    使用0'0' 之一,例如:

    FigureModel::create(array('worldwideoffices' => 1, 'worldwideemployees' => 0));
    FigureModel::create(array('worldwideoffices' => 1, 'worldwideemployees' => '0'));
    

    但如果更有意义,最好使用null

    注意:如果您从其他来源插入数据,只需在 php 中使用强制转换为整数:

    FigureModel::create(array(
        'worldwideoffices'   => (int) $offices,
        'worldwideemployees' => (int) $employees,
    ));
    

    【讨论】:

    • 我真的没有看到他的第一个命令FigureModel::create( array( 'worldwideoffices'=>1, 'worldwideemployees'=> null ) ); 有问题,如果该列可以为空,Laravel/Postgres 应该接受 null。
    • @AntonioCarlosRibeiro 这就是我写的原因 但如果它更有意义,最好使用 null - 但在某些情况下,它会产生影响(例如 null 意味着N/A - 没有意义,但0 表示有意义,但为零)
    猜你喜欢
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-03-18
    • 2019-12-05
    相关资源
    最近更新 更多