如何在 Laravel eloquent 中将 int 转换为字符串?

sam*_*toh 1 php mysql type-conversion laravel eloquent

我的 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 
Run Code Online (Sandbox Code Playgroud)

如果 mysql 查询我使用这个:CONVERT(b.id,CHAR)将 int 转换为 string

如何在 Laravel eloquent 中将 int 转换为字符串?我正在使用 Laravel 5.3。

我曾尝试过这样的:

$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();
Run Code Online (Sandbox Code Playgroud)

但这不起作用

Tim*_*sen 6

如果您想使用非常自定义的连接条件,例如涉及一列或两列的强制转换的连接条件,那么我不确定如果至少没有某种原始语法,这是否可行。因此,您应该考虑@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();
Run Code Online (Sandbox Code Playgroud)

请注意,我做了以下更改:

  • 用于DB::raw()为计数提供自定义别名
  • 添加location.nameGROUP BY(和选择)子句
  • 使用另一个DB::raw()来处理连接条件中的强制转换