Laravel错误:违反完整性约束

时间:2020-03-02 08:28:48

标签: mysql database laravel laravel-5

路线
Route::post('/review','RentalController@review');
控制者
public function review(Request $request)
{
    $review = new Reviews();
    $rpId = rand();
    $review->rvid=$rpId;
    $review->usid_fk = Auth::user()->uid;
    // $propId= $request->input('propId');
    $review->prId_fk = $request->input('propId');
    $review->comment = $request->input('comment');
    $review->rating = $request->input('rating');
    $review->date = Carbon::now();
    $review->save();
}
迁移档案
public function up()
{
    Schema::create('review', function (Blueprint $table) {
        $table->integer('rvId')->primary();
        $table->integer('usId_fk');
        $table->foreign('usId_fk')->references('uid')->on('users');
        $table->integer('prId_fk');
        $table->foreign('prId_fk')->references('pId')->on('properties');
        $table->date('date');
        $table->integer('rating');
        $table->string('comment');
    });
}
查看(刀片模板)
<form action="{{ url('/review') }}" method="POST">
    {{ csrf_field() }}

    <div class="modal-body">
        <input type="hidden" name="propid" value="{{ $prop->propid }}"/>
        <input id="rating" name="rating" class="rating rating-loading" data-show-clear="false" data-min="0" data-max="5" data-step="1" value="0">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text">Comment</span>
            </div>
            <textarea name="comment" class="form-control" aria-label="Comment"></textarea>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>

该错误是违反完整性约束的错误。

prId_fk不能违反null完整性约束

我已经尝试解决了几天。我一直试图一遍又一遍地重写我的代码,但还是没用。您的答复将不胜感激。

谢谢!

2 个答案:

答案 0 :(得分:1)

您正在从表单中以propid的形式发送数据,但是正在尝试以propId的形式在控制器中访问数据。确保大小写匹配。

将表单中的输入更改为

<input type="hidden" name="propId" value="{{ $prop->propid }}"/>

或更新您的控制器以引用正确的索引。

$review->prId_fk = $request->input('propid');

答案 1 :(得分:0)

您收到此错误,是因为根据您的迁移文件,您的prId_fk不接受空值,并且您的隐藏输入文件名为propid,并且您使用propId进行了访问

您可以将prId_fk设置为在迁移文件中接受null,如下所示

$table->integer('prId_fk')->nullable();

正确访问

$request->input('propid');
相关问题