Support the ongoing development of Laravel.io →
posted 10 years ago
Eloquent

Hello --

I would like to add a function to my model:

(assume a blog where users have posts, and posts have comments)

class Posts extends Eloquent { protected $table = 'posts';

public function comment_count() {
    return $this->hasCount('comments', 'post_id', 'post_id');
}

}

and then query a user with all of its posts, and a comment count on each of their posts- using something along the lines of:

User::with(array("posts", "posts.comment_count"))->get();

I could easily make it users with all posts, and posts with all comments, but if there are a lot of comments and I don't need the data, I would rather just get the count.

Any thoughts or direction to go?

Thanks, Todd

Last updated 3 years ago.
0

There a similar thread here
http://laravel.io/forum/05-03-2014-eloquent-get-count-relation

Maybe it will fit your needs

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.