【问题标题】:Select distinct value count laravel选择不同的值计数 laravel
【发布时间】:2014-04-03 14:33:34
【问题描述】:

我有一个订单表,其中有一个状态列。

我正在尝试像这样获取每个状态的计数:

$pending = Order::where('status','=','pending')->count();
$active = Order::where('status','=','active')->count();

但这并不高效,因为必须为每种状态类型调用一次。

如何减少查询次数?

【问题讨论】:

    标签: sql laravel


    【解决方案1】:

    发出 SQL 请求:

    SELECT count(DISTINCT `status_id`) FROM `dbname`.orders WHERE `user_id` = '2';
    

    在 Laravel 中,您可以尝试以下操作:

    $user->orders()->distinct()->count(["status_id"]);
    

    【讨论】:

    • 这值得更多的支持。我看到很多人都做错了——这是正确的方法。
    【解决方案2】:

    你可以试试

    $orders = Order::select(DB::raw('count(*) as order_count, status'))
      ->groupBy('status')
      ->get();
    

    【讨论】:

      【解决方案3】:

      这是你的写作方式->

      $users= DB::table('table_name')->distinct()->get(['column_name']);
      $users_count = $users->count();
      

      【讨论】:

      • 你用我的查询为我节省了很多:$DB::selectRaw('distinct field')->count();而你的回答是我对这糟糕的一天的唯一回答。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-27
      • 2018-05-28
      • 2013-03-20
      • 2013-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多