我正在尝试建立一个论坛,用户可以在该论坛上发布主题,并且用户可以在主题的底部对主题进行评论,但是当我将评论部分添加到主题时,它会引发SQLSTATE[42S02]
错误正在尝试使用来自laravel https://laravel.com/docs/5.8/eloquent-relationships的Morph关系源,以便将线程连接到相应的线程或注释。最终产品必须像Reddits的http://prntscr.com/mwvors一样,评论之间必须互为注释,并且可以对其他评论进行评论。
编辑:
php artisan migrate
之后,它更新了迁移,但给出了此错误
错误
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'comments.commmentable_id' in 'where clause' (SQL: select * from `comments` where `comments`.`commmentable_id` = 1 and `comments`.`commmentable_id` is not null and `comments`.`commmentable_type` = App\Thread) (View: C:\Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\resources\views\thread\single.blade.php
single.blade.php
{{--Answers/comments--}}
<div class="comment-list">
@foreach($thread->comments as $comment)
<h4>{{$comment->body}}</h4>
<lead>{{$comment->user->name}}</lead>
@endforeach
</div>
<div class="comment-form">
<form action="{{ route('threadcomment.store', $thread->id) }}" method="post" role="form">
{{csrf_field()}}
<h4>Create Comment</h4>
<div class="form-group">
<input type="text" class="form-control" name="body" id="" placeholder="Input...">
</div>
<button type="submit" class="btn btn-primary">Comment</button>
</form>
</div>
用户模型
public function threads(){
return $this->hasMany(Thread::class);
}
线程模型
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->morphMany(Comment::class,'commmentable');
}
评论模型
public function commenttable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo(User::class);
}
评论控制器
public function addThreadComment(Request $request, Thread $thread)
{
$this->validate($request,[
'body' => 'required|min:10|max:250'
]);
$comment = new Comment();
$comment->body = $request->body;
$comment->user_id = auth()->user()->id;
$thread->comments()->save($comment);
}
web.php
Route::resource('comment','CommentController', ['only' =>['update','destroy']]);
Route::post('comment/create/{thread}','ThreadController@storeComment')->name('threadcommment.store');
答案 0 :(得分:0)
代码中有错别字
public function comments()
{
return $this- >morphMany(Comment::class,'commmentable');
}
Route::post('comment/create/{thread}','ThreadController@storeComment')->name('threadcommment.store');
三倍MMM,而不是2毫米