82

Here is my query using fluent query builder.

    $query = DB::table('category_issue')
        ->select('issues.*')
        ->where('category_id', '=', 1)
        ->join('issues', 'category_issue.issue_id', '=', 'issues.id')
        ->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
        ->group_by('issues.id')
        ->order_by(DB::raw('COUNT(issue_subscriptions.issue_id)'), 'desc')
        ->get();

As you can see, I am ordering by a count from the joined table. This is working fine. However, I want this count returned with my selections.

Here is the my raw sequel query that works fine.

Select issues.*, COUNT(issue_subscriptions.issue_id) AS followers 
FROM category_issue JOIN Issues ON category_issue.issue_id = issues.id 
LEFT JOIN issue_subscriptions ON issues.id = issue_subscriptions.issue_id
WHERE category_issue.category_id = 1
GROUP BY issues.id
ORDER BY followers DESC

How would I go about this select using Laravel's fluent query builder? I am aware I can use a raw sql query but I would like to avoid that if possible.

2 Answers 2

138
+50

You can use an array in the select() to define more columns and you can use the DB::raw() there with aliasing it to followers. Should look like this:

$query = DB::table('category_issue')
    ->select(array('issues.*', DB::raw('COUNT(issue_subscriptions.issue_id) as followers')))
    ->where('category_id', '=', 1)
    ->join('issues', 'category_issue.issue_id', '=', 'issues.id')
    ->left_join('issue_subscriptions', 'issues.id', '=', 'issue_subscriptions.issue_id')
    ->group_by('issues.id')
    ->order_by('followers', 'desc')
    ->get();
1
  • 3
    In modern Laravel you can use selectRaw and pass in a string of your SQL selectors like ->selectRaw('issues.*, COUNT(issue_subscriptions.issue_id) as followers'): laravel.com/docs/8.x/queries#selectraw Commented Oct 1, 2021 at 17:31
54
$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

3
  • 2
    ahh yes, I was aware of this. Except, I was hoping to do it in a single query similar to the raw sequel I posted. This approach would require me to loop through my data and count it for each row (each row's count can and will be different). Any other ideas? Thanks for the help!
    – Alex Naspo
    Commented Nov 5, 2012 at 13:28
  • 2
    How do you access count? $count[0]->count ?
    – Dan
    Commented Aug 1, 2014 at 10:45
  • 3
    @Silver89 just like this: echo $count.
    – hkucuk
    Commented May 3, 2016 at 17:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.