如何将MySQL查询转换为Laravel 4中的DB builder?

时间:2015-08-01 08:34:34

标签: laravel-4

如何将MYSQL查询转换为Laravel sql查询?

SELECT *
FROM (
    SELECT 
        year(invoiceDate) as [year],left(datename(month,invoicedate),3)as [month], 
        InvoiceAmount as Amount 
    FROM Invoice
) as s
PIVOT
(
    SUM(Amount)
    FOR [month] IN (jan, feb, mar, apr, 
    may, jun, jul, aug, sep, oct, nov, dec)
)AS pivot

请任何人使用这些方法将上述代码写入Laravel DB Builder格式。

例如:$pivot=DB::table('Invoice')->where()...

以及eg: $pivote=Invoice::where()->..

如何编写 pivot 的代码?

1 个答案:

答案 0 :(得分:0)

以下是如何使用DB:rawDB::select

实施代码的方式
$results =
    DB::select(
        DB::raw("
          SELECT *
            FROM (
                SELECT 
                    year(invoiceDate) as [year],left(datename(month,invoicedate),3)as [month], 
                    InvoiceAmount as Amount 
                FROM Invoice
            ) as s
            PIVOT
            (
                SUM(Amount)
                FOR [month] IN (jan, feb, mar, apr, 
                may, jun, jul, aug, sep, oct, nov, dec)
            )AS pivot
        ")
    );

注意:这是为了展示/演示如何根据您在问题中的请求将sql语句放入DB::raw,但这并不意味着我已经检查了您的sql语句。 / p>