【问题标题】:Laravel 1048 Column cannot be NULL on storing dataLaravel 1048 Column 在存储数据时不能为 NULL
【发布时间】:2014-06-24 16:26:35
【问题描述】:

当我尝试保存新联系人时,我收到了1048 Column 'username' cannot be NULL 错误。很明显,此错误的原因是 username 的空值,但是我想让它工作而不将列设置为 NULL 或检查 username POST 数据是否为空,然后将其值设置为 '' .

我见过很多示例,其中列未设置为 NULL 和/或数据未设置为'',然后才保存到数据库。

或者也许我错了,我错过了什么?

我希望有人可以对此发表评论..

$contact = new Contact;
$contact->name      = Input::get('name'); 
$contact->username  = Input::get('username');
$nerd->save();

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    为输入变量设置默认的非空值。

    $contact = new Contact;
    $contact->name     = Input::get('name');
    $contact->username = Input::get('username', '');
    $contact->save();
    

    或者,在最近的 Laravel 版本中:

    $contact = new Contact;
    $contact->name     = $request->input('name');
    $contact->username = $request->input('username', '');
    $contact->save();
    

    【讨论】:

      【解决方案2】:

      您可以使用模型事件 (http://laravel.com/docs/eloquent#model-events)。

      当Contact为creatingupdating时,可以测试username是否为null,修改为''后再写入DB。

      【讨论】:

      • 这是一个答案。今后,请务必提供代码来展示如何解决发帖人的问题。
      【解决方案3】:

      我也遇到过同样的问题。视图页面中的“字段名”和数据库的列名无关。我的问题是:

      "Integrity constraint violation: 1048 Column 'MoneyMethod' cannot be null".
      

      我的查看页面输入标签:

      {!! Form::select("MoneyMethod", $MoneymethodInfo, null,["class"=>"form-control MoneyMethod required","id"=>"MoneyMethod"]) !!},
      

      注意我的数据库表 $table->string('MoneyMethod', 100); 中“MoneyMethod”的拼写,money Method 的拼写与视图页面相同,但在我的控制器中

      $riskfund->Moneymethod  = Input::get('Moneymethod');
      

      仔细查看“Moneymethod”的拼写与视图页面和数据库表列不同。更正拼写后,它现在可以工作了。

      所以,请检查表单、控制器、数据库表中“用户名”的拼写。

      【讨论】:

        猜你喜欢
        • 2022-10-18
        • 2022-11-04
        • 1970-01-01
        • 1970-01-01
        • 2015-11-03
        • 2022-12-12
        • 2017-05-05
        • 2013-09-25
        相关资源
        最近更新 更多