将MySql隐藏查询到Laravel

时间:2018-03-20 12:21:31

标签: laravel-5

请你帮我写一下Laravel Raw Query for Mysql查询。

SELECT 
    SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS `business_email_template_10_open`,
    SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`
   FROM dummy_email_track d 
       join recommend_email_send_by_cron r on d.user_id = r.user_id
       join user_form_submission u on r.user_id = u.id'
  where d.business_id = $businessId

3 个答案:

答案 0 :(得分:1)

如果您无法使用存储过程,请忽略我的回答。

我认为你不能使用Laravel QueryBuilder导致某些原因(我有类似的情况)。如何使用SP(存储过程)?

Mysql SP

CREATE DEFINER=`your_mysql_id`@`%` PROCEDURE `get_usage_business_email_template`()
__SP:BEGIN
    BEGIN
        SELECT
            SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS `business_email_template_10_open`,
            SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`
        FROM dummy_email_track d 
            join recommend_email_send_by_cron r on d.user_id = r.user_id
            join user_form_submission u on r.user_id = u.id'
        WHERE d.business_id = $businessId
    END;
END

并且,Laravel将此SP称为如下

$result = DB::select('CALL get_usage_business_email_template()');

我希望你能节省你的时间,因为我的答案......

答案 1 :(得分:0)

这应该会给你一个开端!

https://laravel.com/docs/5.6/database#running-queries

$results = DB::select('select * from users where id = :id', ['id' => 1]);

确保为where子句提供正确的id。所以在你的情况下它会是这样的:

(where d.business_id = :businessId, ['businessId' => 1])

古德勒克!

答案 2 :(得分:0)

请试试这个:

$data = DB::table('dummy_email_track as d')
        ->select('d.*','r.*','u.*')
        ->selectRaw('SUM(IF(d.business_email_template_10_open = "Yes", 1,0)) AS business_email_template_10_open')
        ->selectRaw('SUM(IF(d.business_email_template_11_open = "Yes", 1,0)) AS `business_email_template_11_open`')
        ->leftJoin('recommend_email_send_by_cron as r','d.user_id', '=', 'r.user_id')
        ->leftJoin('user_form_submission as u', 'r.user_id', '=', 'u.id')
        ->where('d.business_id','=', $businessId)
        ->get();