我无法将Mysql查询转换为laravel查询生成器

时间:2019-05-20 07:11:58

标签: php mysql laravel laravel-query-builder

我正在努力将下面的MySQL查询转换为laravel查询生成器。它内部有很多联接和子查询。有人可以帮我吗?

MYSQL查询:

SELECT  a.id , b.*, a.agent_id, td.contacts, td.addresses 
FROM teams a  
left join team_details as td on td.team_id = a.id
    LEFT OUTER JOIN
    (
        SELECT m.id, m.due_date, t.team_id, m.department, m.assigned_to , cm.title, u.name
        FROM (
            SELECT team_id, MAX(due_date) AS due_date
            FROM campaign_activities where task_status=false and due_date is not null
            GROUP BY team_id
            ) t JOIN campaign_activities m ON m.team_id = t.team_id AND t.due_date = m.due_date
            left join campaign_activity_masters cm on cm.id = m.camp_activity_id  
            left join users u on u.id = m.assigned_to 
    ) b ON a.id = b.team_id  
order by a.id

我正在尝试类似下面的操作,但是由于LEFT OUTER JOIN里面有子查询,所以被卡住了:)。

DB::table('teams as a')
->leftjoin('team_details as td', 'td.team_id','=','a.id')
->select('a.id', 'b.*', 'a.agent_id','td.contacts','td.addresses')
->leftouterjoin(DB::select(DB::raw('SELECT m.id, m.due_date, t.team_id, m.department, m.assigned_to , cm.title, u.name
FROM (
    SELECT team_id, MAX(due_date) AS due_date
    FROM campaign_activities where task_status=false and due_date is not null
    GROUP BY team_id
    ) t JOIN campaign_activities m ON m.team_id = t.team_id AND t.due_date = m.due_date
    left join campaign_activity_masters cm on cm.id = m.camp_activity_id  
    left join users u on u.id = m.assigned_to')))
->get();

有什么建议吗?我想为此查询构建器应用分页功能paginate()而不是get()

1 个答案:

答案 0 :(得分:0)

我认为您应该尝试。

$cards = DB::select("SELECT  a.id , b.*, a.agent_id, td.contacts, td.addresses 
FROM teams a  
left join team_details as td on td.team_id = a.id
    LEFT OUTER JOIN
    (
        SELECT m.id, m.due_date, t.team_id, m.department, m.assigned_to , cm.title, u.name
        FROM (
            SELECT team_id, MAX(due_date) AS due_date
            FROM campaign_activities where task_status=false and due_date is not null
            GROUP BY team_id
            ) t JOIN campaign_activities m ON m.team_id = t.team_id AND t.due_date = m.due_date
            left join campaign_activity_masters cm on cm.id = m.camp_activity_id  
            left join users u on u.id = m.assigned_to 
    ) b ON a.id = b.team_id  
order by a.id");

希望它能对您有所帮助。