What is the difference between the Eloquent and DB classes in Laravel5.2?

Source: Internet
Author: User
Please give an example. thank you! Please give an example. thank you!

Reply content:

Please give an example. thank you!

This answer is taken from my blog article: laravel study Notes-data and model start article (https://www.insp.top/article/learn-laravel-database-and-model-foundation) for you to delete this question, want to know more directly read the original.

First, let's take a look at the database components (that is, Eloquent ORM)

Database components are divided into three layers:

  • Database connection layer

  • Query construction layer

  • Application layer

Let's take a look at what each layer has and what part of the corresponding document:

Database connection layer

The database connection layer is the basis for the entire database component dependency. this is self-evident, but this part isDocumentWe can see that it is more based onPDOProvides the following functions:

  • More intuitive and easy-to-use transactions

  • Read/write splitting

  • Compatibility and switch between multiple database drivers

  • Database Events

This part of functions can be quickly called through Facade (DB class). the document already describes, obviously, as long as it is usedPDOOr MySQLi can quickly use the parameter binding and SQL preprocessing functions. To facilitate event processing, this section encapsulates a method for each of the add, delete, modify, and query operations. In fact, the calling methods are the same (all are encapsulated PDO and PDOStatement class methods ), the types of results are different.

This layer is very low-level. users who need to directly write SQL statements to operate databases can access this layer. In most cases, transactions are not directly used, we will talk about it in a later article ). It should be noted that, as the underlying layer, all functions behind the database components are implemented using this layer, so this layer must be understood.

Query construction layer

Query constructorQuery constructorAnd(Syntax) generatorIt is a bridge between the application layer and the underlying layer. It provides a smooth access interface, allowing developers to create queries in an elegant form. Although modern frameworks provide such functions, few such functions are implemented by using many excellent PHP features such as Laravel.

You can query in this way:


  where('score', '>', 0)                           ->where(function (Builder $query) {                               $query->where('code', 'foo')                                     ->orWhere('name', 'like', 'Anvi%');                           })->skip(1)                           ->take(5)                           ->get();

The following SQL statement is generated:

SELECT * FROM users WHERE score > 0 AND (code = 'foo' OR 'name' LIKE 'Anvi%') OFFSET 1 LIMIT 5;

As you can see, the query constructor at the query constructor provides a very intuitive access method, which greatly reduces the error probability of building SQL statements, we can easily encapsulate a certain type of query method (this function will be mentioned later) to improve development efficiency.

Always remember that the where or groupBy methods used are all the methods provided by the query constructor. this must be clarified during development, which method is provided by the instance object of the layer and class, which helps avoid unnecessary errors.

The query constructor provides an elegant access method, and the final output SQL statement is the (syntax) generator, which generates the corresponding SQL statement based on the currently selected database driver, finally, the query constructor combines the parameters used for binding and calls the database connection layer to return the query results.

In fact, the query constructor has two database components. one is the basic native query constructor provided by the query constructor and the other is the version encapsulated by the Eloqent ORM,Provides more advanced Association query methods

Application layer

This layer is part of our long-term use. this layer includes three major components:Eloquent ORM,Migration,Schema.

These three are implemented based on the query constructor layer, with the highest field rate. of course, the last two are also very important, namely data migration and Structure Generator. The data migration component and structure generator actBest component CPUsually in pairs.

As an application layer, it must be implemented based on more underlying components, that is where you are confused. As a matter of fact, it is better to figure it out. it is nothing more than that the ORM encapsulates and provides more functions (mainly associated queries ).

One is to operate as an orm model (more elegant), and the other is to directly operate on the returned dataset ?! My own understanding...

Eloquent is an ORM, while DB directly uses native SQL operations.
Eloquent:Post::where('id','<',3)->orderBy('id','desc')->take(1)->get();
DB:DB::insert('insert into users (id, name, email, password) values (?, ?, ? , ? )', [1, 'Laravel','laravel@test.com','123']);
For details about the DB facade, refer to: Laravel database instance tutorial-using the DB facade to operate the database

Eloquent is an ORM that can help us automate many tasks, but not all of them, such as handling direct ing relationships between tables and simplifying SQL.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.