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

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

Susan Sarandon
Release: 2024-12-25 13:32:55
Original
524 people have browsed it

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
Copy after login

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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template