ITZone

Query data from Database in Laravel

Eloquent ORM and Query Builder

WHAT?

HOW?

Eloquent

In Eloquent, each table in the database must correspond to a model. Note that each Eloquent model must extend Illuminate\Database\Eloquent\Model
Return 1 Eloquent Collections, where each result is 1 object.

Query builder

Query Builder builds a DB class to execute queries. Therefore, to start a Query Builder, we use the table() function on the DB facade.

Return 1 result array , where each result is 1 object StdClass by PHP

To see the expressions the query builder supports, run the following code and you will see that there are many supported queries:

COMPARE?

Eager Loading

WHAT?

When we use ORM in laravel, by default ORM will be in “lazy” mode when loading all relational models. Let’s take a look at an example

And there is a piece of code like this:

Looking at the example above we will see:

=> So for n comment records we will need N+1 query, a huge number of queries

HOW?

Laravel has provided us with 2 methods load() and with() to deal with the above problem.

Eager loading with method with()

The executed query will be like this:

Chúng ta nhận ra điểm mạnh của phương thức này là chúng ta thay vì phải tốn N+1 query thì chúng ta sẽ chỉ tốn 2 query.

If you need to specify more conditions in the query, do the following:

Eager loading with load() method

We get the same execution query as using with()

Difference between with() and load()?

We will see that

How to use?

Share the news now