代码之家  ›  专栏  ›  技术社区  ›  TheRealPapa

Laravel雄辩的“have”和计算列

  •  0
  • TheRealPapa  · 技术社区  · 6 年前

    我的控制器中有以下逻辑,它在 having 陈述没有 $type 步骤数据按预期显示(因此 addSelect 按预期工作)。我该如何过滤 使用计算列 meters_count ?

    SQLSTATE[42703]: Undefined column: 7 ERROR: column "meters_count" does not exist
    

    守则:

    // Get all customers visible to this user
    $query = Site::with('customer.logo', 'mainContact', 'address')
        ->addSelect(['meters_count' => Meter::selectRaw('COUNT(*)')->whereColumn('meters.site_id', 'sites.id')]);
    
    // Filter for user type
    switch ($type) {
    
        case 'deleted':
            $query->onlyTrashed();
            break;
    
        case 'no_meters':
            $query->groupBy('sites.id')
               ->having('meters_count', '=', 0);
            break;
    
        default:
            $query->groupBy('sites.id')
               ->having('meters_count', '>', 0);
    }
    
    // Run query here...
    $sites = $query-get();
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   TheRealPapa    6 年前

    // Get all customers visible to this user
    $query = Site::with('customer.logo', 'mainContact', 'address')
        ->withCount('meters');
    
    // Filter for user type
    switch ($type) {
    
       case 'deleted':
            $query->onlyTrashed();
            break;
    
       case 'no_meters':
            $query->groupBy('sites.id')
                ->havingRaw('(SELECT COUNT(*) FROM meters WHERE meters.site_id = sites.id) = ?', [0]);
            break;
    
       default:
            $query->groupBy('sites.id')
                ->havingRaw('(SELECT COUNT(*) FROM meters WHERE meters.site_id = sites.id) > ?', [0]);
        }
    
    }
    
    // Run query here...
    $sites = $query->get();
    
        2
  •  0
  •   William Lie    6 年前

    在应用之前,需要应用GroupBy函数

    $users = DB::table('users')
                    ->groupBy('account_id')
                    ->having('account_id', '>', 100)
                    ->get();
    

    https://laravel.com/docs/7.x/queries