从模型中设置Laravel表单中的空值

时间:2017-02-10 14:27:11

标签: laravel-5.3

在我的客户模型中,我有以下两个函数,在创建新客户时处理空字段:

public function setCustPstAttribute($custpst)
{
    $this->attributes['CustPST'] = trim($custpst) == '' ? 0 : trim($custpst);
}

    public function setCustSicAttribute($custsiccode){
    $this->attributes['CustSicCode'] = trim($custsiccode) == '' ? 0 : trim($custsiccode);
}

函数setCustPstAttribute($ custpst)工作正常,你可以看到上面的0值。根本不会访问/输入setCustSicAttribute($ custsiccode)函数,我尝试退出该函数,并且永远不会访问它。唯一的区别是变量类型,$ custpst是varchar而$ custsiccode是int。 sql insert正在寻找一个整数,但是获取一个空字符串。

QueryException {#363 ▼
  #sql: "insert into `customers` (`CustCompanyName`, `CustSicCode`, `FOBLocation`, `CustPST`, `CustGenerator`, `CustStatus`, `CustLastUpdate`, `CustStartDate`) values (?, ?, ?, ?, ?, ?, ?, ?)"
  #bindings: array:8 [▼
    0 => "Test"
    1 => ""
    2 => "Selkirk"
    3 => 0
    4 => ""
    5 => "Active"
    6 => "2017-02-10 14:12:48"
    7 => "2017-02-10 14:12:48"
  ]
  #message: "SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '' for column 'CustSicCode' at row 1 (SQL: insert into `customers` (`CustCompanyName`, `CustSicCode`, `FOBLocation`, `CustPST`, `CustGenerator`, `CustStatus`, `CustLastUpdate`, `CustStartDate`) values (fgfgf, , Selkirk, 0, , Active, 2017-02-10 14:12:48, 2017-02-10 14:12:48))"
  #code: "22007"
  #file: "/var/www/laravel/vendor/laravel/framework/src/Illuminate/Database/Connection.php"
  #line: 770
  -previous: PDOException {#364 ▶}
  +errorInfo: array:3 [▼
    0 => "22007"
    1 => 1366
    2 => "Incorrect integer value: '' for column 'CustSicCode' at row 1"
  ]
  +"previous": PDOException {#364 ▶}
  -trace: {▶}
}

1 个答案:

答案 0 :(得分:0)

函数的名称(在set和Attribute之间)必须与数据库中的列名完全相同。将 CustSicCode 属性。更新后,它工作。感谢