"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Efficiently Select from Subqueries Using Laravel's Query Builder?

How Can I Efficiently Select from Subqueries Using Laravel's Query Builder?

Posted on 2025-03-23
Browse:960

How Can I Efficiently Select from Subqueries Using Laravel's Query Builder?

Laravel query constructor efficiently handles subqueries

]

When using Eloquent ORM to retrieve data from subqueries, developers often use toSql() and native queries in combination. Although this method is effective, it is not intuitive enough. Here is a more efficient solution:

For example, to extract the result count from the following subquery:

SELECT COUNT(*) 
FROM (
  SELECT * 
  FROM abc 
  GROUP BY col1
) AS a;

Laravel allows us to merge native queries into Eloquent queries using mergeBindings. First, we create an Eloquent Builder instance for the subquery:

$sub = Abc::where(..)->groupBy(..);

Then, we use DB::table to create a new table that references the subquery and manually set the corresponding binding:

$count = DB::table( DB::raw("({$sub->toSql()}) as sub") )
    ->mergeBindings($sub->getQuery()) // 获取底层查询构造器
    ->count();

This approach ensures that the correct binding is applied to the merged query, resulting in the result we want without manually performing string operations.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3