3

In writing a custom query that returns users with their posts grouped and a count with the total posts made by them

query in SQL

SELECT users.nameUser, COUNT(posts.namePost) AS Total, GROUP_CONCAT(posts.namePost) AS List
FROM users
JOIN posts ON users.id = posts.user_id
GROUP BY users.nameUser;
+----------+-------+-----------------------+
| nameUser | Total | List                  |
+----------+-------+-----------------------+
| alfa     |     2 | PHP 7,Aire comprimido |
| beta     |     2 | HTML 5,MySQL 8        |
+----------+-------+-----------------------+

The question is, how can build this query with Eloquent Laravel or even with it query Builder?

1

2 Answers 2

1

You can pass raw query string as DB statement:

$data = DB::statement('
    SELECT users.nameUser, COUNT(posts.namePost) AS Total, 
    GROUP_CONCAT(posts.namePost) AS List
    FROM users
    JOIN posts ON users.id = posts.user_id
    GROUP BY users.nameUser
')->get();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Do you have set User and Post models with relation between?
yeah I was forgotten it, both tables have a relationship
I wondered could you use something like User::with('posts')->all() and then use some of helper functions available to filter or sort result.
1

This is only a way to do it, using Eloquent ORM and for certain tasks using Fluent

$data = User::select('users.nameUser')
           ->selectRaw('COUNT(posts.namePost) AS Total')
           ->selectRaw('GROUP_CONCAT(posts.namePost) AS List')
           ->join('posts', 'users.id', '=', 'posts.user_id')
           ->groupBy('users.nameUser')
           ->get();

Useful stuff

  1. You can use selectRaw() method instead of DB::raw() method
  2. I use the User model to avoid include more query builder code
  3. I use groupBy() method

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.