2017-08-15 27 views
0

私はコメント付き投稿ページを作成しようとしています。しかし、システムが投稿IDを認識しないため、投稿にコメントを追加すると機能しません。Laravelモデルが動作しません

SQLSTATE[HY000]: General error: 1364 Field 'post_id' doesn't have a default value (SQL: insert into comments (body , updated_at , created_at) values (This is a test comment, 2017-08-15 19:51:47, 2017-08-15 19:51:47))

コメントフォーム

<div class="well"> 
    <h4>Leave a Comment:</h4> 

    <form role="form" method="post" action="{{ $post->id }}/comments"> 
    {{ csrf_field() }} 

     <div class="form-group"> 
      <textarea name="body" class="form-control" rows="3"></textarea> 
     </div> 

     <button type="submit" class="btn btn-primary">Submit</button> 
    </form> 
</div> 
:それはpost_idのは、私は次のエラーを取得しています$ post_idの

に等しいことを知らないことを私は私が間違ってやっています

ROUTE

Route::post('/posts/{post}/comments', '[email protected]'); 

CONTROLLER

public function store(Post $post) 
{ 
    $post->addComment(request('body')); 

    return back(); 
} 

COMMENTモデル

class Comment extends Model 
{ 
    protected $fillable = ['body']; 

    public function post() 
    { 
     return $this->belongsTo(Post::class); 
    } 
} 

Postモデル

class Post extends Model 
{ 
    public function addComment($body) 
    { 
     Comment::create([ 
      'body' => $body, 
      'post_id' => $this->id 
     ]); 
    } 

    public function comments() 
    { 
     return $this->hasMany(Comment::class); 
    } 
} 
+0

(下記参照) – mattchambers

答えて

4

post_idが充填可能な配列ではありません:あなたのpost_idのがあることを確認してMySQLでのテーブル内の

class Comment extends Model 
{ 
    protected $fillable = ['body', 'post_id']; //<--- 
    ... 
} 
0

自動増分または「null」にすることができます。このエラーは、post_idに値がなく、デフォルトにできないことを示しています。あなたのコードのpost_idのの表情から

は、あなたの主キーですが、私が見る

0

は、お使いのコントローラ機能は、あなたが話してポスト知っているdoen't自動インクリメントに設定されていません。あなたはそれがあなたのためにIDを記入しますあなたのフォームから戻って来ているポストIDを使用してポストを検索する必要がありLaravel Docs 5.4 Eloquentに示すように、あなたはこの

$comment = new App\Comment(['message' => 'A new comment.']); 

$post = App\Post::find(1); 

$post->comments()->save($comment); 

のような新しいコメントを保存することができます。

また、私が正しく覚えていれば、記入可能フィールドの配列に['post_id']を追加する必要はありません。

SQLエラーは、「列修飾子」を使用して解決できます。ポストモデルで充填可能な配列にpost_idのと体を追加してみてください

Schema::table('users', function (Blueprint $table) { 
    $table->string('email')->nullable(); 
}); 

Laravel Docs 5.4 Migrations

関連する問題