如何使用Laravel Eloquent在两个表之间创建子查询

时间:2017-12-29 10:26:50

标签: php mysql laravel rest eloquent

大家好我是Laravel开发的新手,我想知道如何在两个表之间创建子查询,例如,我想执行这个查询:

SELECT 
users.*, 
LEAST(
    MIN(
        CASE WHEN orders.date_end >= CURDATE() THEN orders.date_end ELSE "9999-99-99 99:99:99" END
    ), 
    MIN(
        CASE WHEN orders_others.date_to >= CURDATE() THEN orders_others.date_to ELSE "9999-99-99 99:99:99" END
    ), 
    MIN(
        CASE WHEN orders.priority_date >= CURDATE() THEN orders.priority_date ELSE "9999-99-99 99:99:99" END
    )
) as next_order, 
MIN(
    CASE WHEN orders.date_end >= CURDATE() THEN orders.date_end ELSE "9999-99-99 99:99:99" END
) AS next_ending, 
MIN(
    CASE WHEN orders_others.date_to >= CURDATE() THEN orders_others.date_to ELSE "9999-99-99 99:99:99" END
) AS next_order_others, 
MIN(
    CASE WHEN orders.priority_date >= CURDATE() THEN orders.priority_date ELSE "9999-99-99 99:99:99" END
) as next_priority_date
FROM 
`users` 
LEFT JOIN `orders` ON `orders`.`idu` = `users`.`id` 
LEFT JOIN `orders_others` ON `orders_others`.`unique` = `orders`.`unique` 
AND `orders_others`.`date_to` >= (
    CURDATE() - INTERVAL 1 YEAR
) 

GROUP BY 
`users`.`id` having `next_order` >= '2017-12-30 00:00:00' 
ORDER BY 
`next_order` ASC 
LIMIT 10

我测试它并且它可以正常工作,我想知道如何在Laravel雄辩中写出它

1 个答案:

答案 0 :(得分:5)

假设您的模型名为Contract,您可以使用以下语法来实现您的目标:

Contracts::where('trainer_id', '1')
    ->orWhere(function ($subquery) {
        $subquery->whereIn('id', function ($query) {
            $query->select('contract_id')
                ->from('trainees')
                ->where('user_id', '1');
        })
    })->get();