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

不言
Release: 2023-03-31 22:38:02
Original
1893 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!