列postqs_id不能为null

时间:2017-10-27 14:11:21

标签: php mysql laravel

我有postqs表和回复表。 postqs_id是foriegn key in reply table。为什么我得到这个错误?以及如何解决它

  

SQLSTATE [23000]:完整性约束违规:1048列' postqs_id'不能为空(SQL:插入reply_qsreplypostqs_idupdated_atcreated_at)值(kk ,, 2017-10-27 13: 54:03,2017-10-27 13:54:03))

控制器:

 public function store(Request $request)
 {
   $reply = new Reply_qs();
   $reply->reply = $request->get('reply');
   $reply->postqs_id = $request->get('postqs_id');
   $postqs=$reply->postqs()->get();
   $reply->save();

    return redirect()->route('postqs.show')
                    ->with('success','Your question created successfully');
 }

postqs Model:

 public function reply_qs(){
    return $this->hasMany('App\Reply_qs');
   }

reply_qs型号:

 public function postqs(){
 return $this->belongsTo('App\Postqs', 'postqs_id', 'id');
    }

迁移:

  Schema::create('reply_qs', function (Blueprint $table) {

        $table->increments('id')->unique();
        $table->text('reply');
        $table->timestamps('date');

       $table->integer('postqs_id')->unsigned();
       $table->foreign('postqs_id')->references('id')->on('postqs') -
      >onDelete('cascade')->onUpdate('cascade');
    });

刀片文件:

   <form action="{{ route('postqs.store') }}" method="POST" class="form-
     horizontal">
   {{ csrf_field() }}

         <div class="form-group">
           <label class="control-label col-sm-2" >Reply:</label>
                <div class="col-sm-7">
                  <textarea name="reply" id="reply" class="form-control"></textarea>
              </div>
           </div>
   <input type="submit" class="btn btn-primary" value="Submit" >

2 个答案:

答案 0 :(得分:1)

因此,在澄清之前不要使用假设......

这是您的路线示例:

Route::get('/url/{id}', 'SomeController@view')->name('postqs.show');

Route::post('/reply/{id}', 'Reply_qsController@store')->name('postqs.store');

你的路线会/看起来像这样。

因此,在控制器中,您可以:

public function store(Request $request, $id)
{
    $storeIt = $request->get();

    MODELNAME::create([
        'reply' => $storeIt['reply'],
        'postqs_id' => $id
        //Other entries here if required
    ]);

    return redirect()->route('postqs.show')
        ->with('success', 'Your question has been created');
}

需要将MODELNAME更改为您打算将信息存储到的相关表格的模型。

答案 1 :(得分:-1)

只需编辑您的表单

<form action="{{ route('postqs.store') }}" method="POST" class="form-
   horizontal">
     {{ csrf_field() }}
<input name="postqs_id"  display="hidden" class="form-control" value=
 {{$postqs_id}} />
     <div class="form-group">
       <label class="control-label col-sm-2" >Reply:</label>
            <div class="col-sm-7">
              <textarea name="reply" id="reply" class="form-control"></textarea>
           </div>
        </div>
 <input type="submit" class="btn btn-primary" value="Submit" >