需要帮助将sql查询转换为laravel查询

时间:2019-11-13 10:06:58

标签: mysql laravel-5

我需要在laravel查询中使用以下sql查询,或者如何直接运行到laravel中。谢谢

SELECT  t.*
FROM    (SELECT client_id,product_name, max(real_date) AS max_date
        FROM api_hilbertis.transactions
        WHERE active = 1 AND real_date <= '2019-03-01'
        GROUP BY client_id, product_name) AS m

INNER JOIN api_hilbertis.transactions AS t
        ON t.client_id = m.client_id
        AND t.product_name = m.product_name
        AND t.real_date = m.max_date
        AND active = 1
ORDER BY real_date DESC;

1 个答案:

答案 0 :(得分:0)

您可以使用laravel原始查询。 示例HERE

因此,对于您的情况,我们可以这样写:

$results = DB::select( DB::raw("
SELECT  t.*
FROM    (SELECT client_id,product_name, max(real_date) AS max_date
        FROM api_hilbertis.transactions
        WHERE active = 1 AND real_date <= '2019-03-01'
        GROUP BY client_id, product_name) AS m

INNER JOIN api_hilbertis.transactions AS t
        ON t.client_id = m.client_id
        AND t.product_name = m.product_name
        AND t.real_date = m.max_date
        AND active = 1
ORDER BY real_date DESC"
 ));

编辑:带有变量的示例:

$someVariable = $request->input('some_variable');

$results = DB::select( DB::raw("SELECT * FROM some_table WHERE some_col = :somevariable"), 
['somevariable' => $someVariable,]
);