public function comments() { return $this->hasMany('Comment'); } [1] > $post = Post::first(); // object(Post)( // 'incrementing' => true, // 'timestamps' => true, // 'exists' => true // ) [2] > $post->comments->count();// 4 [3] > $post->comments()->count();// 4 $posts = Post::leftJoin('comments', 'comments.post_id', '=', 'posts.id') ->select('posts.*', 'count(*) as commentsCount') ->groupBy('posts.id') ->get(); $posts = Post::with('commentsCount')->get(); public function comments() { return $this->hasMany('Comment'); } public function commentsCount() { return $this->comments() ->selectRaw('post_id, count(*) as aggregate') ->groupBy('post_id'); } $post = Post::with('commentsCount')->first(); $post->commentsCount; $post->commentsCount->first(); $post->commentsCount->first()->aggregate; public function commentsCount() { return $this->hasOne('Comment') ->selectRaw('post_id, count(*) as aggregate') ->groupBy('post_id'); } public function getCommentsCountAttribute() { if ( ! array_key_exists('commentsCount', $this->relations)) $this->load('commentsCount'); $related = $this->getRelation('commentsCount'); return ($related) ? (int) $related->aggregate : 0; } $post = Post::first(); $post->commentsCount; // 4 $posts = Post::with('commentsCount')->get(); $posts->first()->commentsCount; Source: https://habr.com/ru/post/302000/
All Articles