简体   繁体   中英

I'm not able to convert the Mysql query into laravel query builder

I'm struggling to convert this below MySQL query into laravel query builder. It has a lot of joins and subqueries inside. Can someone please help me?

MYSQL query:

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

I'm trying something like below but got stuck with LEFT OUTER JOIN as it has sub query inside :).

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();

Any suggestions, please? I want to apply paginate function paginate() instead of get() for this query builder.

I think you should try.

$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");

Hope it help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM