Home > Database > Mysql Tutorial > How to Efficiently Select from Subqueries Using Laravel's Query Builder?

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

Linda Hamilton
Release: 2025-01-12 07:08:43
Original
319 people have browsed it

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

Select data from subqueries using the Laravel query builder

Question: Retrieving the value of a count aggregate from a SQL subquery using Eloquent ORM.

Initial method:

$sql = Abc::from('abc AS a')
    ->groupBy('col1')
    ->toSql();

$num = Abc::from(\DB::raw($sql))
    ->count();
Copy after login

This approach requires manual generation of subquery SQL, which is not ideal.

Best solution:

The Laravel query builder currently lacks a dedicated method for creating subqueries in the FROM clause. Raw statements must be used manually, with proper binding management:

// 定义子查询
$sub = Abc::where(...)->groupBy(...); // Eloquent Builder 实例

// 创建主查询
$count = DB::table(DB::raw("({$sub->toSql()}) AS sub"))
    ->mergeBindings($sub->getQuery()) // 正确合并绑定
    ->count();
Copy after login

Note: Bindings must be merged in the correct order. If additional conditions are added after merging, the order must be adjusted to ensure correct binding.

The above is the detailed content of How to Efficiently Select from Subqueries Using Laravel's Query Builder?. For more information, please follow other related articles on the PHP Chinese website!

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