【发布时间】:2018-03-20 21:24:33
【问题描述】:
大家好,我正在尝试为我网站中的每项服务存储 cmets
首先我创建了用户、评论、服务之间的关系 然后当我尝试添加评论时出现错误:
SQLSTATE[23000]:违反完整性约束:1048 列“services_id”不能为空(SQL:插入comments(body、user_id、services_id、updated_at、@987654326 @) 值 (ggg, 1, , 2018-03-20 21:12:17, 2018-03-20 21:12:17))
这就是服务模型:Service.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Service extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function comments(){
return $this->hasMany('App\comment');
}}
这就是Comment.php的模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
public function services() {
return $this->belongsTo('App\Service');
}}
这就是User.php的模型
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['username', 'email','password','tel','ville','description','image','diplomes','langues',
];
protected $hidden = [
'password', 'remember_token',
];
public function services(){
return $this->hasMany('App\Service');
}
public function comments(){
return $this->hasMany('App\Comment');
}}
路线:
Route::post('/services/{services_id}','CommentsController@store');
在 CommentsController 中存储方法:
public function store(Request $request, $services_id)
{
$this->validate($request,array(
'body'=>'required',
));
$comment=new Comment;
$service=Service::find($services_id);
$comment->body=$request->body;
$comment->user_id=$request->user()->id;
$comment->services()->associate($service);
$comment->save();
$request->session()->flash('notif','success');
return back(); }
这就是刀片页面
<form class="col s12" method="post" action="/services/{$services->id}">
{{ csrf_field() }}
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">insert_comment</i>
<textarea id="textarea1" name="body" class="materialize-textarea"></textarea>
<label for="textarea1" style="color: black;">Commentaire</label>
</div>
</div>
<div class="row">
<div class="col s12 center-align">
<input type="submit" value="confirmer" class="btn-large purple hoverable">
</div>
</div>
</form>
【问题讨论】:
-
你提供了一个空值:
ggg, 1, ,所以$comment->services()->associate($service);必须解析为空 -
是的,我知道它来自它,但我不知道如何纠正它。
-
我们需要查看创建de View的代码。您可能没有发送
$services