我试图找到如何在laravel QueryBuilder或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
表中获取最大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
}
]
}
答案 0 :(得分: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
模式。您可以在database.php
文件中完全禁用它,方法是在MySQL连接下设置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