E
E
Evgeniy Odinets2015-06-03 22:28:58
Laravel
Evgeniy Odinets, 2015-06-03 22:28:58

Why doesn't COUNT work correctly?

Good day.

$posts = self::selectRaw('users.login, posts.*, comments.id, COUNT(comments.id) as comments_count,GROUP_CONCAT(DISTINCT(categories.name)) as cat_name')
                     ->Join('users','users.id', '=', 'posts.author')
                     ->leftJoin('post_cat','post_cat.post_id', '=', 'posts.id')
                     ->leftJoin('categories','categories.id', '=', 'post_cat.cat_id')
                     ->leftJoin('comments','comments.post_id','=','posts.id')
                     ->orderBy('posts.created_at', 'DESC')
                     ->groupBy('posts.id')
                     ->paginate(10);

COUNT(comments.id) considers x2 for some reason, I can't figure out why. If there are 10 comments for a post, then the result displays 20

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Plisko, 2015-06-05
@evgeniy2194

I have another question, why the hell are you sculpting such shit.
self::selectRaw, there is a static stovo that does not break inheritance, and most importantly, you don’t need to use it, because in Laravel the static is chasing through facades and you work with full-fledged objects, you need to use $this.
Eloquent has a normal ORM, which will quickly calculate everything for this request and transparently pull up links, and your code will be difficult to maintain. Respect your colleagues, otherwise they themselves got lost in 3 pines.
Get yourself a debugger or just print the resulting query laravel.com/docs/5.0/database#query-logging to see what happened and what it returns.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question