LoginSignup
1
1

More than 3 years have passed since last update.

Laravel 1対多、子レコードの件数をwithCountを利用して数える

Posted at

やりたいこと

ユーザが何件のコメントを投稿しているかカウントしたい

関係性

User 1

//UserModel
    public function comments() {
        return $this->hasMany(Comment::class);
    }

Comments 多

// CommentModel
    public function user() {
        return $this->belongsTo(User::class);
    }

withCountを利用して取得

$user = User::withCount('comments')->get();

$user->comments_count;

おまけ

カウントは取りたくないけど、コメントしているユーザだけを取得したい

User::has('comments')->get();
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1