hasOne 一对一 用户名-手机号
hasMany 一对多 文章-评论
belongTo 一对多反向 评论-文章
belongsToMany 多对多 用户-角色
hasManyThrough 远程一对多 国家-作者-文章
moreghMany 多态关联 文章/视频-评论
morephToMany 多态多对多 文章/视频-标签
创建评论模型
class Comment extends baseModel
{
public function post(){
return $this->belongsTo('App\Post');
}
/**
* notes: 评论所属用户
* author: cible
* time: 2018/12/4 上午8:44
*/
public function user(){
return $this->belongsTo('App\User');
}
}
增加评论
public function comment(Post $post){
$this->validate(request(),[
'content' => 'required|min:3'
]);
$comment = new Comment();
$comment->user_id = \Auth::id();
$comment->content = request('content');
$post->comments()->save($comment);
return back();
}
评论列表
模型关联预加载(两种)
$books = App\Book::with('author')->get();
$books->load('author','publisher');
//实例
$post->load('User');
模版(直接在模版加载输出)
@foreach($post->comments as $comments)
<li class="list-group-item">
<h5>{{$comments->created_at}} by {{$comments->user->name}}</h5>
<div>
{{$comments->content}}
</div>
</li>
@endforeach
获取评论总数
$posts = App\Post::withCount('comments')->get();
//实例
$lists = Post::orderBy('created_at','desc')->withCount('Comments')->paginate(5);
//视图层
{{$list->comments_count}}