Laravel Subquery Where In
Query:
You need to execute the following query in Laravel:
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
Solution:
To achieve this in Laravel using a subquery, you can employ 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();
Explanation:
The whereIn method allows you to specify that a column's value should match any value in the provided array. In this case, you want to select all products whose id column is present in the product_id column of the product_category table, where the category_id column is either '223' or '15' and the active column is equal to 1.
The provided code uses a closure to define the subquery. Within the closure, you define a query that retrieves the product_id column from the product_category table. The query then filters the results based on the specified conditions and finally returns the desired product_id values.
The above is the detailed content of How to Execute a Subquery WHERE IN Clause in Laravel?. For more information, please follow other related articles on the PHP Chinese website!