0

i have a database named "products" which has a column "categories". This table contain four category of products namely electronic,Decoration,clothes and vehicle. My target to show these category with their count ie:if there are four products belongs to category electronic, then output should be like this :electronic=4 and so on

My code

    public function category()
      {
      $arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
      $data = [];
      foreach($arrayCategorys as $arrayCategory)
       {
      $sql = "SELECT  count(id) FROM products WHERE   categories='$arrayCategory'";
      $records = \DB::select($sql); 
      $data = array_merge_recursive($data, [

                  "{$arrayCategory}" =>isset($records[0]->count),

            ]);
      $data=array_filter($data);
      dd($data);
      }
 }

I want show output like this

'electronic'=>'4',

'Decoration'=>'2',

'clothes'=>'2',

'vehicle'=>'1' according to data in database but iam getting nothing ,[]

2 Answers 2

1

You can GROUP BY your categories like this way when you COUNT

SELECT categories,COUNT(*)  
FROM products 
GROUP BY categories; 

For Idea: http://www.w3resource.com/mysql/aggregate-functions-and-grouping/aggregate-functions-and-grouping-count-with-group-by.php

EDIT: Though i am not familiar with laravel5 syntax but this may work for you

$result = DB::table('products')
            ->select('products.categories', 
                      DB::raw('count(products.id) as category_count')
                    )
            ->orderBy('products.id', 'asc')
            ->groupBy('products.categories')
            ->get();
Sign up to request clarification or add additional context in comments.

2 Comments

how can i use query builder for this in laravel5
@RanjitKarki i have updated my answer. let me know it works for you or not?
0

You used isset($records[0]->count) but the column name for the count will be count(id). Name the count as count like this "SELECT count(id) AS count FROM products WHERE categories='$arrayCategory'". And you wont be able to get the count just by checking if it is set. Remove the isset and just use $records[0]->count. The code should look like:

 public function category()
 {
      $arrayCategorys = ['electronic','Decoration','clothes','vehicle'];
      $data = [];
      foreach($arrayCategorys as $arrayCategory)
       {
      $sql = "SELECT  count(id) AS count FROM products WHERE   categories='$arrayCategory'";
      $records = \DB::select($sql); 
      $data = array_merge_recursive($data, [

                  "{$arrayCategory}" =>$records[0]->count,

            ]);
      $data=array_filter($data);
      dd($data);
      }
 }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.