创建模型Comment.php,为迁移文件添加字段并生成迁移文件,创建控制器类
创建模型Comment.php
php artisan make:model --migration Model/Comment;
添加字段
$table->text ('content')->comment('评论内容');
$table->unsignedInteger ('user_id')->comment('评论用户');
$table->unsignedInteger ('comment_id')->comment('评论id');
$table->string ('comment_type')->comment('评论类型:文章/视频');
运行迁移,生成comments表
php artisan migrate;
创建控制器类CommentController,该模型生成在新建common(公共类)里
artisan make:controller common/CommentController
模板设置
将评论放在一个新的模板中分离出来,comment.blade.php模板,然后在show.blade.php中引入模板,在引入模板时将show页面的$article对象带到comment模板中
@include('common.comment',['model'=>$article])
vue和axios数据提交
@push('js')
@endpush
控制器类CommentController
获取所有评论,把返回值提交给前台,做评论的循环展示
public function index()
{
$model=hd_model();
$comments=$model->comment()->with(['user'])->get();
return ['comments'=>$comments,'code'=>0];
}
添加评论,将评论存到数据库
public function store(Request $request)
{
$model= hd_model();
$data=$request->only(['content']);
$data['user_id']=auth()->id();
$comment= $model->comment()->create($data);
return ['comments'=>$comment->with(['user'])->find($comment['id']),'code'=>0];
}
模型Comment.php,创建一对多关联,获得评论对应的用户
public function user()
{
return $this->belongsTo(User::class);
}
模型Article.php,创建多态关联,获得文章对应的评论个数
public function comment()
{
return $this->morphMany(Comment::class, 'comment');
}
app/helper.php,方法类,获得被点赞的模型对象
function hd_model(){
$model=Request::query('model');
$id=Request::query('id');
$class=str_replace('.','\\',$model);
return $class::find($id);
}