Home >Database >Mysql Tutorial >How to Use Laravel's `whereIn` with a Subquery?

How to Use Laravel's `whereIn` with a Subquery?

Susan Sarandon
Susan SarandonOriginal
2024-12-25 13:32:55526browse

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:

  • Products::whereIn('id', ...) starts the subquery within the WHERE IN clause.
  • The closure function defines the subquery.
  • $query->select('paper_type_id') selects the column to be returned from the subquery.
  • $query->from(with(new ProductCategory)->getTable()) specifies the table to be used in the subquery.
  • $query->whereIn('category_id', ['223', '15']) adds the conditions to the subquery.
  • $query->where('active', 1) adds another condition to the subquery.
  • ->get() retrieves the results.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn