laravel 如何在laravel eloquent中将int转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43842445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I convert int to string in laravel eloquent?
提问by samuel toh
My mysql query is like this :
我的 mysql 查询是这样的:
SELECT b.id, b.name, COUNT(*) AS count_store
FROM stores a
JOIN locations b ON CONVERT(b.id,CHAR) = a.address->'$."regency_id"'
GROUP BY b.id
ORDER BY count_store DESC
LIMIT 10
If mysql query I use this : CONVERT(b.id,CHAR)
to convert int to string
如果 mysql 查询我使用这个:CONVERT(b.id,CHAR)
将 int 转换为字符串
How can I convert int to string in laravel eloquent? I'm using Laravel 5.3.
如何在laravel eloquent中将int转换为字符串?我正在使用 Laravel 5.3。
I had try like this :
我试过这样的:
$stores = Store::select('locations.name','COUNT(*) AS count_store')
->join('locations', 'locations.id', '=', 'stores.address->regency_id')
->groupBy('locations.id')
->orderBy('count_store', 'desc')
->limit(10)
->get();
But it does not work
但它不起作用
回答by Tim Biegeleisen
If you want to use a very custom join condition, such as one involving a cast of one or both columns, then I'm not sure this would be possible without at least somekind of raw syntax. Hence, you should consider the answer given by @Rodrane as well as this one:
如果您想使用非常自定义的连接条件,例如涉及一列或两列的强制转换,那么我不确定如果没有至少某种原始语法,这是否可行。因此,您应该考虑@Rodrane 给出的答案以及这个答案:
$stores = Store::select('locations.id', 'locations.name', DB::raw('COUNT(*) AS count_store'))
->join('locations', DB::raw("CONVERT(locations.id, CHAR)"), '=', 'stores.address->regency_id')
->groupBy('locations.id', 'locations.name')
->orderBy('count_store', 'desc')
->limit(10)
->get();
Note that I made the following changes:
请注意,我进行了以下更改:
- Used
DB::raw()
to give a custom alias to the count - Added
location.name
to theGROUP BY
(and select) clause - Used another
DB::raw()
to handle the cast in the join condition
- 用于
DB::raw()
为计数提供自定义别名 - 添加
location.name
到GROUP BY
(和选择)子句 - 使用另一个
DB::raw()
来处理连接条件中的转换