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

Hi I want to run the following query with the query builder ... this is what i have

Query

    SELECT 
    taggedUserName, count(taggedUserId) AS freq
FROM
    feedMentions
WHERE
    postId IN (SELECT postId FROM feedPosts WHERE postedByUserName = 'User Name')
GROUP BY taggedUserId
ORDER BY freq DESC;

Query Builder

    $users = DB::table("feedMentions")
                ->select(
                    DB::raw('taggedUserName'),
                    DB::raw('COUNT(taggedUserId) AS freq')
                )
                ->where(
                    DB::raw("postId IN (SELECT postId FROM feedPosts WHERE postedByUserName = '{$userId}') ")
                )
                ->groupBy('taggedUserId')
                ->orderBy('freq', 'DESC');
                    
    return $users;

The query builder query is giving an error. I know I'm doing something wrong but cant spot it.

Last updated 3 years ago.
0
Solution

Hi Haseeb, You should not use the user input directly inside a raw query expression. Neways I hope this solves your problem:

    $users = DB::table("feedMentions")
                ->select(
                    DB::raw('taggedUserName'),
                    DB::raw('COUNT(taggedUserId) AS freq')
                )
                ->whereRaw(DB::raw('postId IN (SELECT postId FROM feedPosts WHERE postedByUserName = :userId)'),['userId'=>$userId])
                ->groupBy('taggedUserId')
                ->orderBy('freq', 'DESC')->get();
Last updated 3 years ago.
0

Thanks a lot

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Haseeb90 haseeb90 Joined 8 Apr 2014

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.