Home > Backend Development > PHP Tutorial > Detailed explanation of the use of Eloquent object-relational mapping in PHP's Laravel framework, laraveleloquent_PHP tutorial

Detailed explanation of the use of Eloquent object-relational mapping in PHP's Laravel framework, laraveleloquent_PHP tutorial

WBOY
Release: 2016-07-12 08:58:15
Original
915 people have browsed it

Detailed explanation of the use of Eloquent object-relational mapping in PHP's Laravel framework, laraveleloquent

Zero, what is Eloquent
Eloquent is Laravel's 'ORM', that 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, which makes the Model class very convenient to call.
Let’s take a look at the following code:

<&#63;php

class Article extends \Eloquent {

protected $fillable = [];

}

Copy after login

'protected $fillable = [];' This line of code has no value here. It is automatically generated by the generator and 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, there are only two meaningful things in this file: '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
Eloquent Chinese documentation is at: http://laravel-china.org/docs/eloquent

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

Find the article with id 2 and print its title

$article = Article::find(2);

echo $article->title;

Copy after login

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

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

echo $article->id;

Copy after login

Query all articles and print out all titles in a loop

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

foreach ($articles as $article) {

  echo $article->title;

}

Copy after login

Find all articles with id between 10~20 and print all titles

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

foreach ($articles as $article) {

  echo $article->title;

}

Copy after login

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

$articles = Article::where('id', '>', 10)->where('id', '<', 20)->orderBy('updated_at', 'desc')->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. The latter will result in 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' calls, that is, 'Article::where().. .' and 'Article::....->where()'.

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

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

Intermediate operation flow, please see the code:

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

The `::where()->where()->orderBy()` in this code 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? It's easy, use the following code:

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

Then you will see the following error:

2016226161019074.jpg (929×97)

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

The “Terminator” method

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

`first()` `get()` `paginate()` `count()` `delete()` are some of the more commonly used "terminator" methods. They will appear at the end of the intermediate operation flow. , call the SQL to the database, get the returned data, and return an Article object or a collection of a group of Article objects after processing.

Examples of complex usage

Copy code The code is as follows:

Article::where('id', '>', '100')->where('id', '<', '200')->orWhere('top', 1) ->belongsToCategory()->where('category_level', '>', '1')->paginate(10);

3. Relationships (associations) between models
1. One-to-one relationship

As the name suggests, this describes 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 have 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 like this :

user: id ... ... account_id

account: id ... ... user_id

Copy after login

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

<&#63;php

class User extends Eloquent {

 

 protected $table = 'users';

 public function hasOneAccount()

 {

   return $this->hasOne('Account', 'user_id', 'id');

 }

}

Copy after login

Then, when we need to use this relationship, how should we use it? As follows:

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

The `$account` obtained at this time is an instance of the `Account` class.

这里最难的地方在于后面的两个 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() 关系,应该这么写:

<&#63;php

class Account extends Eloquent {

 protected $table = 'accounts';

 

 public function belongsToUser()

 {

  return $this->belongsTo('User', 'user_id', 'id');

 }

}

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`:

<&#63;php

class User extends Eloquent {

 

 protected $table = 'users';

 public function hasManyPays()

 {

  return $this->hasMany('Pay', 'user_id', 'id');

 }

}

Copy after login

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

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

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

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

<&#63;php

class Pay extends Eloquent {

 protected $table = 'pays';

 

 public function belongsToUser()

 {

  return $this->belongsTo('User', 'user_id', 'id');

 }

}

Copy after login

3.多对多关系

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

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

article: id ... ...

tag: id ... ...

article_tag: article_id tag_id

Copy after login

在 Model 中使用:

<&#63;php

class Tag extends Eloquent {

 protected $table = 'tags';

 

 public function belongsToManyArticle()

 {

  return $this->belongsToMany('Article', 'article_tag', 'tag_id', 'article_id');

 }

}

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, 'video_hierarchy', 'video_id', 'video_parent_id');

}

public function children_video()

{

  return $this->belongsToMany($this, 'video_hierarchy', 'video_parent_id', 'video_id');

}

Copy after login

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

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

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

直接上代码:

$users = User::with('hasOneAccount')->take(10)->get()
Copy after login

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

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

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

您可能感兴趣的文章:

  • Laravel 5框架学习之Eloquent 关系
  • Laravel 5框架学习之Eloquent (laravel 的ORM)
  • Laravel模板引擎Blade中section的一些标签的区别介绍
  • Laravel 5.0 发布 新版本特性详解
  • Laravel实现用户注册和登录
  • 推荐几款用 Sublime Text 开发 Laravel 所用到的插件
  • 跟我学Laravel之视图 & Response
  • 跟我学Laravel之安装Laravel
  • 跟我学Laravel之快速入门
  • Laravel框架表单验证详解
  • Laravel框架中扩展函数、扩展自定义类的方法
  • Laravel框架路由配置总结、设置技巧大全
  • PHP开发框架Laravel数据库操作方法总结

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1104331.htmlTechArticle详解PHP的Laravel框架中Eloquent对象关系映射使用,laraveleloquent 零、什么是 Eloquent Eloquent 是 Laravel 的 'ORM',即 'Object Relational Mapping',对象关系...
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