


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, which makes the Model class very convenient to call.
Let’s take a look at the following code:
<?php class Article extends \Eloquent { protected $fillable = []; }
'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;
Find the article titled "I am the title" and print the id
$article = Article::where('title', '我是标题')->first(); echo $article->id;
Query all articles and print out all titles in a loop
$articles = Article::all(); // 此处得到的 $articles 是一个对象集合,可以在后面加上 '->toArray()' 变成多维数组。 foreach ($articles as $article) { echo $article->title; }
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; }
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; }
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 '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 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();
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;
Then you will see the following error:
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. , send 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
Article::where('id', '>', '100')->where('id', '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
假设我们需要在 User 模型中查询对应的 Account 表的信息,那么代码应该是这样的。 `/app/models/User.php`:
<?php class User extends Eloquent { protected $table = 'users'; public function hasOneAccount() { return $this->hasOne('Account', 'user_id', 'id'); } }
然后,当我们需要用到这种关系的时候,该如何使用呢?如下:
$account = User::find(10)->hasOneAccount;
此时得到的 `$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 = 'accounts'; public function belongsToUser() { return $this->belongsTo('User', 'user_id', 'id'); } }
2.一对多关系
学会了前面使用一对一关系的基础方法,后面的几种关系就简单多了。
我们引入一个新的Model:Pay,付款记录。表结构应该是这样的:
user: id ... ... pay: id ... ... user_id
User 和 Pay 具有一对多关系,换句话说就是一个 User 可以有多个 Pay,这样的话,只在 Pay 表中存在一个 `user_id` 字段即可。 `/app/models/User.php`:
<?php class User extends Eloquent { protected $table = 'users'; public function hasManyPays() { return $this->hasMany('Pay', 'user_id', 'id'); } }
然后,当我们需要用到这种关系的时候,该如何使用呢?如下:
$accounts = User::find(10)->hasManyPays()->get();
此时得到的 `$accounts` 即为 `Illuminate\Database\Eloquent\Collection` 类的一个实例。大家应该也已经注意到了,这里不是简单的 `-> hasOneAccount` 而是 `->hasManyPays()->get()`,为什么呢?因为这里是 `hasMany`,操作的是一个对象集合。
相应的 belongsTo() 的用法跟上面一对一关系一样:
<?php class Pay extends Eloquent { protected $table = 'pays'; public function belongsToUser() { return $this->belongsTo('User', 'user_id', 'id'); } }
3.多对多关系
多对多关系和之前的关系完全不一样,因为多对多关系可能出现很多冗余数据,用之前自带的表存不下了。
我们定义两个模型:Article 和 Tag,分别表示文章和标签,他们是多对多的关系。表结构应该是这样的:
article: id ... ... tag: id ... ... article_tag: article_id tag_id
在 Model 中使用:
<?php class Tag extends Eloquent { protected $table = 'tags'; public function belongsToManyArticle() { return $this->belongsToMany('Article', 'article_tag', 'tag_id', 'article_id'); } }
需要注意的是,第三个参数是本类的 id,第四个参数是第一个参数那个类的 id。
使用跟 hasMany 一样:
$tagsWithArticles = Tag::take(10)->get()->belongsToManyArticle()->get();
这里会得到一个非常复杂的对象,可以自行 `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'); }
对,你没有看错,可以 belongsToMany 自己。
其他关系
Eloquent 还提供 “远层一对多关联”、“多态关联” 和 “多态的多对多关联” 这另外三种用法,经过上面的学习,我们已经掌握了 Eloquent 模型间关系的基本概念和使用方法,剩下的几种不常用的方法就留到我们用到的时候再自己探索吧。
重要技巧:关系预载入
你也许已经发现了,在一对一关系中,如果我们需要一次性查询出10个 User 并带上对应的 Account 的话,那么就需要给数据库打 1 + 10 条 SQL,这样性能是很差的。我们可以使用一个重要的特性,关系预载入:http://laravel-china.org/docs/eloquent#eager-loading
直接上代码:
$users = User::with('hasOneAccount')->take(10)->get()
这样生成的 SQL 就是这个样子的:
select * from account where id in (1, 2, 3, ... ...)
这样 1 + 10 条 SQL 就变成了 1 + 1 条,性能大增。

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
