天天看點

laravel模型關聯

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}}