Laravel - 如何将包含串联查询的派生表转换为Eloquent语法?

时间:2017-06-13 14:16:31

标签: mysql sql laravel

如何将以下内容转换为Eloquent语法?我知道那里有一个派生表,所以不确定Laravel中的正确语法是什么?

    SELECT firstname
, CONCAT_WS
( ', '
, CASE WHEN years = 0 THEN NULL ELSE CONCAT(years,' years') END
, CASE WHEN months = 0 THEN NULL ELSE CONCAT(months, ' months') END
, CASE WHEN days = 0 THEN NULL ELSE CONCAT(days, ' days') END
) lengthOfService
FROM
( SELECT firstname
, FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425) years
, FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 - FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12) months
, CEILING((((DATEDIFF(CURDATE(),startdate)/365.2425 - FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12)
- FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 - FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12))* 30) days
FROM users
) x

3 个答案:

答案 0 :(得分:1)

Laravel确实提供了hydrateRaw

首先制作一个模型类,我将使用App \ Models \ MyHydratedUser

$query = "SELECT firstname, CONCAT_WS ( ', '
, CASE WHEN years = 0 THEN NULL ELSE CONCAT(years,' years') END
, CASE WHEN months = 0 THEN NULL ELSE CONCAT(months, ' months') END
, CASE WHEN days = 0 THEN NULL ELSE CONCAT(days, ' days') END
) lengthOfService
FROM
( SELECT firstname
, FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425) years
, FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 - 
FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12) months
, CEILING((((DATEDIFF(CURDATE(),startdate)/365.2425 - 
FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12)
- FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 - 
FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12))* 30) days
FROM users
) x";

$users = App\Models\HydratedUser::hydrateRaw($query);

$ users变量将保存HydratedUser模型集合

答案 1 :(得分:1)

没有使用查询生成器的口才

使用DB::tableDB::raw方法创建子查询并使用selectRaw()

$subQuery = DB::table('users')
    ->selectRaw('firstname,
        FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425) years,
        FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 -
        FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12) months, 
        CEILING((((DATEDIFF(CURDATE(),startdate)/365.2425 - 
        FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12) - 
        FLOOR((DATEDIFF(CURDATE(),startdate)/365.2425 - 
        FLOOR(DATEDIFF(CURDATE(),startdate)/365.2425))* 12))* 30) days');

DB::table(DB::raw('('.$subQuery->toSql().') as tableName')
    ->selectRaw("firstname, CONCAT_WS(', ', 
        CASE WHEN years = 0 THEN NULL ELSE CONCAT(years,' years') END, 
        CASE WHEN months = 0 THEN NULL ELSE CONCAT(months, ' months') END, 
        CASE WHEN days = 0 THEN NULL ELSE CONCAT(days, ' days') END) lengthOfService")

答案 2 :(得分:0)

Eloquent没有提供这样的具体方法。您需要使用DB::raw("...")(但我认为这不是解决方案)或DB::select("SELECT ...");