将MySQL查询转换为Laravel

时间:2018-10-16 09:10:33

标签: mysql laravel

如何将这个MySQL查询转换为Laravel查询?

select *
from marques
where id in (select marque_id from products
             where category_id = 'valeur1' or category_id in (select id from categories
                                                              where parent_id = 'Valeur1'))

1 个答案:

答案 0 :(得分:1)

我认为您当前的查询等同于以下内容:

SELECT *
FROM marques m
LEFT JOIN products p
    ON m.id = p.marque_id
LEFT JOIN categories c
    ON p.category_id = c.id AND c.parent_id = 'Valeur1'
WHERE
    p.category_id = 'valeur1' OR
    c.id IS NOT NULL

以下是您的Laravel代码可能是什么样的粗略猜测:

$res = DB::table('marques')
        ->join('products', 'marques.id', '=', 'products.marque_id')
        ->join("categories", function($join) {
            $join->on('products.category_id', '=', 'categories.id')
                 ->on('categories.parent_id', '=', 'Valeur1')
        })
        ->whereNotNull('categories.id')
        ->orWhere('products.category_id', '=', 'valeur1')
        ->select('*')
        ->get();