如何使用查询生成器计算 laravel 中的回访客户(超过 1 次)?
How to count revisited customer ( more than 1 time) in laravel using query builder?
我需要统计一个月内的回访客户。这意味着需要计算 customer_id 在一个月内在 table 中有多个条目。
我的查询只显示了客户总数。
$count_customer_current_month = DB::table("customer_entry")->whereRaw('MONTH(date) = ?',
[$currentMonth])->count();
只需使用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');
如果你想知道有多少这样的客户:
$entry_customers->get()->count() // count the collections.
或使用子查询获取客户数量:
DB::table(DB::raw("({$entry_customers->getSql()}) AS entry_customer"))
->mergeBindings($entry_customers)
->count();
查看月份的另一种方法:
DB::table("customer_entry")->whereMonth('date', '=',$currentMonth)->select(DB::raw('COUNT(customer_id)'))->groupBy('customer_id')->havingRaw("COUNT(customer_id) > 1")->get()
您可以通过不同的方法解决这个问题。
您可以创建单独的 table 或将列(已访问)添加到您的登录 table。
每当用户登录时,访问次数加一。
架构
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->unique();
$table->integer('visited')->default('0');
每当用户登录时,将此访问字段加一
也许是这样
Model::selectId($userId)->whereMonth('visit', '=', $month)->count();
- 你得到模型
- Select 您模型的
user
通过它的 ID
- 按月过滤
- 数数
有了这个你会得到一个整数表示特定用户记录访问的总次数
我需要统计一个月内的回访客户。这意味着需要计算 customer_id 在一个月内在 table 中有多个条目。
我的查询只显示了客户总数。
$count_customer_current_month = DB::table("customer_entry")->whereRaw('MONTH(date) = ?',
[$currentMonth])->count();
只需使用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');
如果你想知道有多少这样的客户:
$entry_customers->get()->count() // count the collections.
或使用子查询获取客户数量:
DB::table(DB::raw("({$entry_customers->getSql()}) AS entry_customer"))
->mergeBindings($entry_customers)
->count();
查看月份的另一种方法:
DB::table("customer_entry")->whereMonth('date', '=',$currentMonth)->select(DB::raw('COUNT(customer_id)'))->groupBy('customer_id')->havingRaw("COUNT(customer_id) > 1")->get()
您可以通过不同的方法解决这个问题。 您可以创建单独的 table 或将列(已访问)添加到您的登录 table。 每当用户登录时,访问次数加一。
架构
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->unique();
$table->integer('visited')->default('0');
每当用户登录时,将此访问字段加一
也许是这样
Model::selectId($userId)->whereMonth('visit', '=', $month)->count();
- 你得到模型
- Select 您模型的
user
通过它的 ID - 按月过滤
- 数数
有了这个你会得到一个整数表示特定用户记录访问的总次数