Laravel在连接语句中使用MAX

问题描述 投票:0回答:1

我试图找到如何在laravel Query Builder或Eloquent join语句中使用MAX,例如:

$userShoppings = \DB::table('shoppings')
    ->join('products', 'shoppings.product_id', '=', 'products.id')
    ->select('shoppings.*', 'products.name','products.amount','max(shoppings.ordering_count)')
    ->where('shoppings.user_ordering_ip', request()->ip())
    ->get();

在这段代码中我想从ordering_count方法上的shoppings表获得max select,但是我收到此错误:

Column not found: 1054 Unknown column 'max(shoppings.ordering_count)' in 'field list' 

任何人都可以帮我解决这个问题吗?

更新粘贴错误的结果

Collection {#449 ▼
  #items: array:3 [▼
    0 => {#446 ▼
      +"id": 11
      +"product_id": 25
      +"user_ordering_ip": "127.0.0.1"
      +"ordering_count": 3
      +"created_at": "2017-12-25 09:41:01"
      +"updated_at": "2017-12-25 09:41:01"
      +"amount": "128,440"
      +"max(shoppings.ordering_count)": 3
    }
    1 => {#445 ▼
      +"id": 10
      +"product_id": 26
      +"user_ordering_ip": "127.0.0.1"
      +"ordering_count": 1
      +"created_at": "2017-12-25 09:32:13"
      +"updated_at": "2017-12-25 09:32:13"
      +"amount": "137,614"
      +"max(shoppings.ordering_count)": 1
    }
    2 => {#452 ▼
      +"id": 9
      +"product_id": 49
      +"user_ordering_ip": "127.0.0.1"
      +"ordering_count": 2
      +"created_at": "2017-12-24 17:59:29"
      +"updated_at": "2017-12-24 18:35:25"
      +"amount": "110,092"
      +"max(shoppings.ordering_count)": 2
    }
  ]
}
laravel laravel-5 eloquent
1个回答
0
投票

你可以使用DB::raw()。所以:

$userShoppings = \DB::table('shoppings')
    ->join('products', 'shoppings.product_id', '=', 'products.id')
    ->select('shoppings.*', 'products.name','products.amount', DB::raw('max(shoppings.ordering_count)'))
    ->where('shoppings.user_ordering_ip', request()->ip())

    // note: you'll need to also group by all the columns
    // you're select in `shoppings.*`

    ->groupBy('products.name', 'products.amount', 'shoppings.id')
    ->get();

https://laravel.com/docs/5.5/queries#raw-expressions

对于您遇到的groupBy()问题,您可能已为MySQL启用了strict模式。您可以通过在MySQL连接下设置database.php,在strict => false文件中完全禁用它。但是,这将禁用所有严格检查

如果你想简单地禁用ONLY_FULL_GROUP_BY,你可以在modes中为你的mysql连接添加一个database.php密钥,如下所示:

modes'     => [
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_AUTO_CREATE_USER',
                'NO_ENGINE_SUBSTITUTION'
            ]

这将明确启用其他检查,但省略ONLY_FULL_GROUP_BY

© www.soinside.com 2019 - 2024. All rights reserved.