代码之家  ›  专栏  ›  技术社区  ›  Devin Dixon

Laravel违反了具有默认值的非空约束

  •  0
  • Devin Dixon  · 技术社区  · 6 年前

    我对Laravel和默认值有问题。我在表中创建了字段,如下所示:

    $table->string('title', 255)->default('');
    

    在模型中,我再次使用了一个默认设置:

     protected $attributes = [
            'title' => '',
        ];
    

    但是我总是得到这个错误:

    sqlstate[23502]:非空冲突:7错误:列中有空值 “标题”违反了非空约束详细信息:失败的行包含 (3dd07c7a-e3f3-4f20-8d16-0f066b219dc2,dsfs,sdfs,空,空, sdfs,空,0,0,0,0,0,0,空,空)。(SQL:插入到 “用户”(“标题”、“名字”、“姓氏”、“电子邮件”、“业务单元”, “linkedin_profile”)值(,dsfs,sdfs,sdfs,)返回 “用户ID”)

    我的缩写保存操作(例如,未经验证)如下:

    $data = Input::all();
    $user = new Users($data);
    $user->save();
    

    以下是$data:

    array (size=12)
      '_token' => string '0EI9JGmgiNDAqmv83pdQZaktyWNLiX3GB9JQSfvA' (length=40)
      'first_name' => string 'ads' (length=3)
      'last_name' => string 'asd' (length=3)
      'email' => string 'asd' (length=3)
      'title' => null
      'business_unit' => null
      'linkedin_profile' => null
      'is_admin' => string '0' (length=1)
      'is_employee' => string '0' (length=1)
      'is_manager' => string '0' (length=1)
      'is_trainer' => string '0' (length=1)
      'rt' => string '/users' (length=6)
    

    为什么我的默认值没有被设置?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Chin Leung    6 年前

    问题是数据库列不允许标题为空值。

    您可以这样允许他们:

    $table->string('title')->nullable()->default('');
    

    或者即使没有默认将其作为 NULL 默认情况下:

    $table->string('title')->nullable();
    

    否则,必须确保标题不为空。


    如果不希望允许空值并将其自动转换为空字符串,可以向模型中添加类似这样的赋值函数:

    public function setTitleAttribute($title)
    {
        $this->attributes['title'] = is_null($title) ? '' : $title;
    }
    

    更多信息: https://laravel.com/docs/5.6/eloquent-mutators

        2
  •  0
  •   Mtxz    6 年前

    因为“title”键在提供的数组中,所以它将尝试插入它:您应该能够插入空值。

    你可以用一个 mutator setTitleAttribute($val) 方法,或者只需在插入前取消设置“title”数组键(如果该值为空)。您还可以使用集合帮助器或数组过滤器进行筛选,以删除未设置的所有空值。