为什么在插入新数据时出现错误?

时间:2019-04-25 23:02:24

标签: php laravel voyager

我试图通过使用同一控制器添加一个新输入来覆盖Voyager视图“编辑-添加视图”。
但是当我尝试添加新数据时,我会遇到此错误。

  

“ SQLSTATE [HY000]:常规错误:1364字段'Category_id'没有   默认值(SQL:插入到“用户”(“名称”,“电子邮件”,   `password`,`role_id`,`updated_at`,`created_at`)值(ali12345,   ali12345@ali12345.com,   $ 2y $ 10 $ qrHhwTFhnjluM7heNE.WCOwSbFIVsag4GWJzunZQGSLgdcXD2r21a,3,   2019-04-25 22:45:45,2019-04-25 22:45:45))“

我曾尝试在模型中添加可填充内容,但没有解决方案。

protected $fillable = [
            'id',
            'role_id',
            'name',
            'email',
            'avatar',
            'password',
            'remember_token',
            'settings',
            'created_at',
            'updated_at',
            'Category_id'
        ];

1 个答案:

答案 0 :(得分:0)

首先,问题是因为您没有在表中设置 Category_id 的默认值。

如果您确定请求中具有 Category_id 字段,请确保在插入新记录时传递所有必填字段。

让我为您提供一些处理您的情况的示例(以下代码块应位于您的 Controller 中)。另外,我将以我最喜欢的方式为您插入新记录。

使用输入外观:

public function create(Request $request)
{
    $user = new User;

    $user->username = Input::get('role_id');
    $user->name = Input::get('name');
    $user->email = Input::get('email');
    $user->password = Hash::make(Input::get('password'));
    $user->Category_id = Input::get('Category_id');
    $user->save();

    return Redirect::back();
}

这是我最喜欢的一种方式:

public function create(Request $request)
{
    $user = new User;

    $data = $this->cleanUnfillableFields($request->all(), $user->getFillable());

    $user->create($data);

    return Redirect::back();
}

/**
* This removes/unsets fields that are not fillable from the model.
* This is the magic method where you should put in a separate class or a trait,
* so all controllers can share this method.
*
* @param array $data
* @param array $fillableFields
*
* @return array
*/
protected function cleanUnfillableFields(array $data, array $fillableFields): array
{
    foreach ($data as $key => $value) {
      if (! in_array($key, $fillableFields))
        unset($data[$key]);
    }

    return $data;
}

使用上述方法,只要正确设置了可填充字段并且您的请求中有必填字段,您就无需再麻烦地填写每个模型的属性并过滤掉不必要的字段。