【问题标题】:Laravel error : Integrity constraint violationLaravel 错误:违反完整性约束
【发布时间】:2020-06-14 12:31:27
【问题描述】:
路线
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 不能为空完整性约束违规

这几天我一直在尝试解决这个问题。我一直在尝试一遍又一遍地重写我的代码,但它仍然没有用。您的回复将不胜感激。

谢谢!

【问题讨论】:

  • 这是因为该列不接受空值..将$table-&gt;integer('prId_fk');更改为$table-&gt;integer('prId_fk')-&gt;nullable();
  • 你确定propid在html表单中不为空吗?
  • 您的迁移包含字段“usId_fk”,但您正在存储属性“usid_fk”。更改。 (我资本,不小)->在控制器中
  • 我将其更新为 $table->integer('prId_fk')->nullable();我试图让 propid 和它在表中为空

标签: mysql database laravel laravel-5


【解决方案1】:

您在表单中以propid 的身份发送数据,但您试图在控制器中以propId 的身份访问它。确保大小写匹配。

要么将表单中的输入更改为

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

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

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

【讨论】:

    【解决方案2】:

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

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

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

    正确访问

    $request->input('propid');
    

    【讨论】:

    • 我已经更改它以使其相同,但我仍然得到“prId_fk' is null
    • pLs 分享$request-&gt;input('propId');;的输出
    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2019-01-02
    • 2017-09-11
    • 2016-05-25
    • 2012-12-26
    相关资源
    最近更新 更多