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

Wednesday, January 26, 2022

[FIXED] How to count revisited customer ( more than 1 time) in laravel using query builder?

 January 26, 2022     laravel, laravel-5, laravel-query-builder, mysql     No comments   

Issue

I need to count revisited customer in one month. It means need to count customer_id has more than one entry in table within a month.

My query is showing only the total customer.

$count_customer_current_month = DB::table("customer_entry")->whereRaw('MONTH(date) = ?', 
                                [$currentMonth])->count();

Solution

Just use group by customer_id having COUNT(customer_id) > 1

$entry_customers = DB::table("customer_entry")
   ->whereRaw('MONTH(date) = ?', [$currentMonth])
   ->groupBy('customer_id')
   ->havingRaw("COUNT(customer_id) > 1")
   ->selectRaw('COUNT(customer_id) AS entry_count, customer_id');

If you want to get how many this customers:

$entry_customers->get()->count() // count the collections.

Or use subquery to get the customers count:

DB::table(DB::raw("({$entry_customers->getSql()}) AS entry_customer"))
   ->mergeBindings($entry_customers)
   ->count();


Answered By - TsaiKoga
  • 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