首页 > 解决方案 > 如何在 Laravel 中使用别名运行子查询?

问题描述

我有以下查询,我正在努力在 Laravel 中使用。DB::raw()在那里但不知道如何设置子查询。

SELECT * from products
where status = 1
AND
id IN (
   SELECT * FROM (
            SELECT `product_id` 
            FROM `order_product` 
        order by `id` desc limit 8
        ) as T
)

我正在使用 Laravel 5.6

标签: phplaravel-5eloquent

解决方案


尚未对其进行测试,但这样的事情应该可以解决问题:

$products = Product
        ::where('status', 1)
        ->whereIn('id', function ($query) {
            $query
                ->select('product_id')
                ->from('order_product')
                ->orderBy('id', 'desc')
                ->take(8);
        })
        ->get();

推荐阅读