Home Backend Development PHP Tutorial About the use of Eloquent object-relational mapping in PHP's Laravel framework

About the use of Eloquent object-relational mapping in PHP's Laravel framework

Jun 13, 2018 pm 02:13 PM
eloquent laravel php

This article mainly introduces the use of Eloquent object-relational mapping in PHP's Laravel framework, focusing on the relationship between Eloquent's data models. Friends in need can refer to it

Zero, what is Eloquent
Eloquent is Laravel's 'ORM', which is 'Object Relational Mapping', object relational mapping. The emergence of ORM is to help us make database operations more convenient.

Eloquent allows a 'Model class' to correspond to a database table, and encapsulates a lot of 'functions' at the bottom layer, making it very convenient to call the Model class.
Look at the following code:

<?php

class Article extends \Eloquent {

protected $fillable = [];

}
Copy after login

'protected $fillable = [];' This line of code has no value here and is automatically generated by the generator. , we will not discuss it here.

This class couldn't be simpler. There is no specified namespace and no constructor. If the meaningless line of code is not included, this file only has two meaningful things: 'Article ' and '\Eloquent'. That's right, Eloquent is so awesome. You only need to inherit the Eloquent class, and you can do many, many things such as 'first() find() where() orderBy()'. This is the powerful power of object-oriented.

1. Basic usage of Eloquent

Without further ado, I will directly show the code of several common usages of Eloquent.

Find the article with id 2 and print its title

$article = Article::find(2);

echo $article->title;
Copy after login

Find the article with the title "I am the title" and print the id

$article = Article::where(&#39;title&#39;, &#39;我是标题&#39;)->first();

echo $article->id;
Copy after login

Query all articles and print out all titles in a loop

$articles = Article::all(); // 此处得到的 $articles 是一个对象集合,可以在后面加上 &#39;->toArray()&#39; 变成多维数组。

foreach ($articles as $article) {

  echo $article->title;

}
Copy after login

Find the id in 10 All articles between ~20 and print all titles

$articles = Article::where(&#39;id&#39;, &#39;>&#39;, 10)->where(&#39;id&#39;, &#39;<&#39;, 20)->get();

foreach ($articles as $article) {

  echo $article->title;

}
Copy after login

Query all articles and print out all titles in a loop, sorted in reverse order by updated_at

$articles = Article::where(&#39;id&#39;, &#39;>&#39;, 10)->where(&#39;id&#39;, &#39;<&#39;, 20)->orderBy(&#39;updated_at&#39;, &#39;desc&#39;)->get();

foreach ($articles as $article) {

  echo $article->title;

}
Copy after login

Basic usage points
1. Every class that inherits Eloquent has two 'fixed usages' 'Article::find($number)' 'Article: :all()', the former will get an object with the value taken out from the database, and the latter will get a collection of objects containing the entire database.

2. All intermediate methods such as 'where()' 'orderBy()', etc. can support both 'static' and 'non-static chaining' calling methods, that is, 'Article::where( )...' and 'Article::....->where()'.

3. All 'non-fixed usage' calls require an operation to 'end'. There are two 'end operations' in this tutorial: '->get()' and '- >first()'.

2. Intermediate operation flow
The word Builder can be literally translated as constructor, but "intermediate operation flow" is easier to understand, because database operations are mostly chain operations. of.

Intermediate operation flow, please see the code:

Article::where(&#39;id&#39;, &#39;>&#39;, 10)->where(&#39;id&#39;, &#39;<&#39;, 20)->orderBy(&#39;updated_at&#39;, &#39;desc&#39;)->get();
Copy after login

The `::where()->where()- of this code >orderBy()` is the intermediate operation flow. The intermediate operation flow is understood using an object-oriented approach and can be summarized in one sentence:

Create an object, continuously modify its properties, and finally use an operation to trigger a database operation.
How to find clues about the intermediate operation flow

There is almost no valuable information in the document about the intermediate operation flow. So, how do we find this thing? Very simple, use the following code:

$builder = Article::where(&#39;title&#39;, "我是标题")->title;
Copy after login

Then you will see the following error:

2016226161019074.jpg (929×97)

Why does an error occur? Because `Article::where()` is still a `Builder` object, not an `Article` object, so it cannot directly access `title`.

"Terminator" method

The so-called "Terminator" method refers to triggering the final database query operation after N intermediate operation flow methods process an Eloquent object. Get the return value.

`first()` `get()` `paginate()` `count()` `delete()` are some of the more commonly used "terminator" methods, they will operate the stream in the middle Finally appears, the SQL is sent to the database, the returned data is obtained, and an Article object or a collection of a group of Article objects is returned after processing.

Complex usage example

Article::where(&#39;id&#39;, &#39;>&#39;, &#39;100&#39;)->where(&#39;id&#39;, &#39;<&#39;, &#39;200&#39;)->orWhere(&#39;top&#39;, 1)->belongsToCategory()->where(&#39;category_level&#39;, &#39;>&#39;, &#39;1&#39;)->paginate(10);
Copy after login

3. Relationship between models (association)
1. One-to-one relationship

As the name suggests, this describes It is a one-to-one relationship between two models. This kind of relationship does not require intermediate tables.

Suppose we have two models: User and Account, corresponding to registered users and consumers respectively. They are a one-to-one relationship. Then if we want to use the one-to-one relationship method provided by Eloquent, the table structure should be It is like this:

user: id ... ... account_id

account: id ... ... user_id
Copy after login

Assuming that we need to query the corresponding Account table information in the User model, the code should be like this. `/app/models/User.php`:

<?php

class User extends Eloquent {

 

 protected $table = &#39;users&#39;;

 public function hasOneAccount()

 {

   return $this->hasOne(&#39;Account&#39;, &#39;user_id&#39;, &#39;id&#39;);

 }

}
Copy after login

然后,当我们需要用到这种关系的时候,该如何使用呢?如下:

$account = User::find(10)->hasOneAccount;
Copy after login

此时得到的 `$account` 即为 `Account` 类的一个实例。

这里最难的地方在于后面的两个 foreign_key 和 local_key 的设置,大家可以就此记住:在 User 类中,无论 hasOne 谁,第二个参数都是 `user_id`,第三个参数一般都是 `id`。由于前面的 `find(10)` 已经锁定了 id = 10,所以这段函数对应的 SQL 为: `select * from account where user_id=10`。

这段代码除了展示了一对一关系该如何使用之外,还传达了三点信息,也是我对于大家使用 Eloquent 时候的建议:

(1). 每一个 Model 中都指定表名

(2). has one account 这样的关系写成 `hasOneAccount()` 而不是简单的 `account()`

(3). 每次使用模型间关系的时候都写全参数,不要省略
相应的,如果使用 belongsTo() 关系,应该这么写:

<?php

class Account extends Eloquent {

 protected $table = &#39;accounts&#39;;

 

 public function belongsToUser()

 {

  return $this->belongsTo(&#39;User&#39;, &#39;user_id&#39;, &#39;id&#39;);

 }

}
Copy after login

2.一对多关系

学会了前面使用一对一关系的基础方法,后面的几种关系就简单多了。

我们引入一个新的Model:Pay,付款记录。表结构应该是这样的:

user: id ... ...

pay: id ... ... user_id
Copy after login

User 和 Pay 具有一对多关系,换句话说就是一个 User 可以有多个 Pay,这样的话,只在 Pay 表中存在一个 `user_id` 字段即可。 `/app/models/User.php`:

<?php

class User extends Eloquent {

 

 protected $table = &#39;users&#39;;

 public function hasManyPays()

 {

  return $this->hasMany(&#39;Pay&#39;, &#39;user_id&#39;, &#39;id&#39;);

 }

}
Copy after login

然后,当我们需要用到这种关系的时候,该如何使用呢?如下:

$accounts = User::find(10)->hasManyPays()->get();
Copy after login

此时得到的 `$accounts` 即为 `Illuminate\Database\Eloquent\Collection` 类的一个实例。大家应该也已经注意到了,这里不是简单的 `-> hasOneAccount` 而是 `->hasManyPays()->get()`,为什么呢?因为这里是 `hasMany`,操作的是一个对象集合。

相应的 belongsTo() 的用法跟上面一对一关系一样:

<?php

class Pay extends Eloquent {

 protected $table = &#39;pays&#39;;

 

 public function belongsToUser()

 {

  return $this->belongsTo(&#39;User&#39;, &#39;user_id&#39;, &#39;id&#39;);

 }

}
Copy after login

3.多对多关系

多对多关系和之前的关系完全不一样,因为多对多关系可能出现很多冗余数据,用之前自带的表存不下了。

我们定义两个模型:Article 和 Tag,分别表示文章和标签,他们是多对多的关系。表结构应该是这样的:

article: id ... ...

tag: id ... ...

article_tag: article_id tag_id
Copy after login

在 Model 中使用:

<?php

class Tag extends Eloquent {

 protected $table = &#39;tags&#39;;

 

 public function belongsToManyArticle()

 {

  return $this->belongsToMany(&#39;Article&#39;, &#39;article_tag&#39;, &#39;tag_id&#39;, &#39;article_id&#39;);

 }

}
Copy after login

需要注意的是,第三个参数是本类的 id,第四个参数是第一个参数那个类的 id。

使用跟 hasMany 一样:

$tagsWithArticles = Tag::take(10)->get()->belongsToManyArticle()->get();
Copy after login

这里会得到一个非常复杂的对象,可以自行 `var_dump()`。跟大家说一个诀窍,`var_dump()` 以后,用 Chrome 右键 “查看源代码”,就可以看到非常整齐的对象/数组展开了。

在这里给大家展示一个少见用法(奇技淫巧):

public function parent_video()

{

  return $this->belongsToMany($this, &#39;video_hierarchy&#39;, &#39;video_id&#39;, &#39;video_parent_id&#39;);

}

public function children_video()

{

  return $this->belongsToMany($this, &#39;video_hierarchy&#39;, &#39;video_parent_id&#39;, &#39;video_id&#39;);

}
Copy after login

对,你没有看错,可以 belongsToMany 自己。
其他关系

Eloquent 还提供 “远层一对多关联”、“多态关联” 和 “多态的多对多关联” 这另外三种用法,经过上面的学习,我们已经掌握了 Eloquent 模型间关系的基本概念和使用方法,剩下的几种不常用的方法就留到我们用到的时候再自己探索吧。

重要技巧:关系预载入
你也许已经发现了,在一对一关系中,如果我们需要一次性查询出10个 User 并带上对应的 Account 的话,那么就需要给数据库打 1 + 10 条 SQL,这样性能是很差的。我们可以使用一个重要的特性,关系预载入:http://laravel-china.org/docs/eloquent#eager-loading

直接上代码:

$users = User::with(&#39;hasOneAccount&#39;)->take(10)->get()
Copy after login

这样生成的 SQL 就是这个样子的:

select * from account where id in (1, 2, 3, ... ...)
Copy after login

这样 1 + 10 条 SQL 就变成了 1 + 1 条,性能大增。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

如何PHP中Laravel框架实现supervisor执行异步进程

PHP的Laravel框架中的event事件操作的解析

The above is the detailed content of About the use of Eloquent object-relational mapping in PHP's Laravel framework. 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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

The Future of PHP: Adaptations and Innovations The Future of PHP: Adaptations and Innovations Apr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Laravel's geospatial: Optimization of interactive maps and large amounts of data Laravel's geospatial: Optimization of interactive maps and large amounts of data Apr 08, 2025 pm 12:24 PM

Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP's Current Status: A Look at Web Development Trends PHP's Current Status: A Look at Web Development Trends Apr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

Laravel and the Backend: Powering Web Application Logic Laravel and the Backend: Powering Web Application Logic Apr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles