PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

[FIXED] How to simplify a SQL "IN" loop query from 1 to multiple IN checks in the same query?

 May 16, 2022     laravel, laravel-5, mysql, php, sql     No comments   

Issue

I'm trying to simplify this part of code where I call a loop DB query to a single DB query that i run a loop over the results afterwards.

My question now is how can I not only get the apps count of one category where a row in the app_categories table exists but the result of every categories count at once?

Current code:

    foreach(DB::Table('categories')->get() as $category)
    {
        $appcount[$category->name] = DB::Table('apps')->where('active', 1)
            ->whereRaw('apps.id in (select app_id from app_categories where category_id = ?)', [$category->id])
            ->count();
    }

Solution

This will suit your needs:

DB::table('categories')
    ->select('categories.id as category_id','categories.name as name',DB::raw('count(*) as apps_count'))
    ->leftJoin('app_categories','categories.id','=','apps_categories.category_id')
    ->leftJoin('apps','apps.id','=','apps_categories.app_id')
    ->where('apps.active',1)
    ->groupBy('categories.id')

Another option could be using eloquent relation.



Answered By - nay
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing