Laravel Query Builder and Eloquent ORM: Concepts, Implementation, and Practical Usage
This article explains Laravel's Query Builder and Eloquent ORM, showing how to convert raw SQL into fluent builder methods, create database tables and models, and demonstrate practical querying techniques with nested conditions, aggregation, and result handling.
Query builder's main advantage is converting SQL keywords such as select, from, where, join, group by, order by, limit, offset, having, and on into class methods, which simplifies SQL usage and greatly reduces the amount of code needed for database operations.
In Laravel, the core functionality resides in two classes: \Illuminate\Database\Query\Builder and \Illuminate\Database\Query\JoinClause .
The article demonstrates how to create the Comment table and its corresponding Eloquent model, providing the full SQL CREATE statement and the PHP model code with appropriate namespaces, use statements, property docblocks, and class definition.
It then presents a practical querying scenario: retrieve comments where the content contains the keyword 'knowledge', the commenter or target user name matches 'soul11201', the replied_root_id is one of 10, 11, or 12, the comment was created within the last seven days, order results by creation date descending, limit to ten rows, and additionally calculate the total number of comments for each replied_root_id.
The raw SQL version of this query is shown, followed by the equivalent Eloquent Builder implementation that uses nested where clauses, loops over the ID list, adds nested queries, applies ordering and limits, and retrieves results with get() and all().
Further sections explain the inner workings of Builder::where, the mixin relationship that allows Builder to delegate methods to the underlying Query Builder, the __call magic method that forwards calls to Query Builder methods, the get() method that executes the query, eager loads relationships, and returns a Collection, and finally the Collection::all() method that returns the wrapped array.
Beike Product & Technology
As Beike's official product and technology account, we are committed to building a platform for sharing Beike's product and technology insights, targeting internet/O2O developers and product professionals. We share high-quality original articles, tech salon events, and recruitment information weekly. Welcome to follow us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.