【问题标题】:Laravel, Integrity constraint violationLaravel,完整性约束违规
【发布时间】:2020-04-22 16:04:20
【问题描述】:

我花了两个小时试图解决这个问题,但没有成功!

我正在尝试保存帖子、标题和图片以及 uder_id,

这是迁移文件:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('user_id');
        $table->unsignedBigInteger('caption');
        $table->string('image');
        $table->timestamps();
    });
}
public function store()
{
    $data= \request()->validate ([

        'caption'=>'required',
        'image'=>'',
    ]);

    auth()->user()->posts()->create($data);

    dd(\request()->all());
}

这是模型

class posts extends Model
{
    protected $guarded = array(
        // Any columns you don't want to be mass-assignable.
        // Or just empty array if all is mass-assignable.
    );
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

这里是视图

<div class="form-group row">

    <label for="caption" class="col-md-4 col-form-label">post Caption</label>
    <input id="caption"
           type="text"
           class="form-control @error('caption') is-invalid @enderror"
           name="caption"
           value="{{ old('caption') }}"
           autocomplete="caption" autofocus>

    @error('caption')
        <span class="invalid-feedback" role="alert">
            <strong>{{ $message }}</strong>
        </span>
    @enderror
    <div>
        <label for="image" class="col-md-4 col-form-label">post_image</label>
        <input type="file" , class="form-control-file" , id="image" ,name="image">

        <div class=" row pt-5">
            <button class="btn btn-primary "> Add new post</button>
        </div>

        @error('image')
            <strong>{{ $message }}</strong>
        @enderror
    </div>
</div>

这是错误

照亮\数据库\查询异常 SQLSTATE [23000]:完整性约束违规:19 NOT NULL 约束失败:posts.image(SQL:插入“posts”(“caption”、“user_id”、“updated_at”、“created_at”)值(hh, 4, 2020 -01-04 09:39:53, 2020-01-04 09:39:53))

希望我们能修复它!

【问题讨论】:

  • captionimage 在您的迁移文件中是必需的。即使您仅根据控制器的要求验证 caption
  • post 是否总是需要图像?
  • @PtrTon 有道理,请阅读错误消息 - 19 NOT NULL constraint failed: posts.image (SQL:... 这意味着在插入帖子时没有图像字段(posts.image)的数据。如果您希望将数据插入到带有空图像或标题的表中,请使它们可以为空或提供数据。虽然我看不到数据应该可以为空的用例......
  • 感谢您的回答,我之所以只按要求验证标题,是因为当我尝试按要求验证图像时,即使我上传了图像,我也会收到消息“图像字段”是必需的',意味着即使我上传它也没有图像数据!我会试着找出原因!
  • 找不到数据图片为空的原因?

标签: laravel sqlite model integrity


【解决方案1】:

在您的帖子表迁移中,更改

$table->string('image');

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

然后在store函数中不要像这样去掉image所需的校验来使image字段需要...

$data= \request()->validate ([

    'caption'=>'required'
]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 2016-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 2020-01-31
    • 2021-03-22
    • 1970-01-01
    相关资源
    最近更新 更多