Home >Database >Mysql Tutorial >How to Use Laravel's `whereIn` with a Subquery?
Laravel Subquery with WHERE IN Clause
A common task in Laravel is to retrieve data using a subquery within a WHERE IN clause. To achieve this, you can utilize the whereIn() method with a closure.
For instance, let's say you have the following query:
SELECT `p`.`id`, `p`.`name`, `p`.`img`, `p`.`safe_name`, `p`.`sku`, `p`.`productstatusid` FROM `products` p WHERE `p`.`id` IN ( SELECT `product_id` FROM `product_category` WHERE `category_id` IN ('223', '15') ) AND `p`.`active`=1
To translate this query into Laravel, you can use the following code:
Products::whereIn('id', function($query){ $query->select('paper_type_id') ->from(with(new ProductCategory)->getTable()) ->whereIn('category_id', ['223', '15']) ->where('active', 1); }) ->get();
In this code:
The above is the detailed content of How to Use Laravel's `whereIn` with a Subquery?. For more information, please follow other related articles on the PHP Chinese website!