laravel 学习笔记 —— 数据和模型起步篇
自上一篇 《laravel 学习笔记 —— 神奇的服务容器》已经有一年了,很多人都问过关于数据库部分的文章什么时候出来。其实不是不想写,而是没法写,因为当时大部分特性都没用到,以至于我无法以笔记形式给出。经过一年时间,laravel 已被我运用在很多类型的项目里,或多或少也对数据库组件了解的比较完整了,是时候完善学习笔记序列重要的环节之一 —— 数据库部分。
Laravel 有三宝,路由、容器和 Eloquent ORM,Eloquent ORM 实际上是 Laravel 框架数据库组件的一个部分,也是最为重要和常用的,所以我们在说 Laravel 数据库组件时,往往指的是 Eloquent ORM。当然,数据库篇的文章肯定要全面讲述,这样有助于理解,也能帮助一些在这一块遇到问题的朋友。
数据库组件是一个比较独立的组件,只依赖很少的东西,通过 composer安装的话,可以在任意一个项目里使用该组件的全部功能,而不需要安装 laravel 框架。具体使用方法可到其 github 主页获取: https://github.com/illuminate/database
由于篇幅有限,且平时很忙,我将会将数据库部分文章拆成包括本篇在内的多篇文章,本文作为概览和文章预告,会对整个数据库组件的构成做一个大致的讲解。
漂亮的结构
Laravel 数据库组件有着明确的分层,虽然没有直白的说明,但仍旧能够从文档结构、代码中明显看得出来。笔者也会按每一层来讲解,当然,由于 Eloquent ORM 占比最高,我将用两个篇幅来着重讲述。
组件大概分了三层:
- 数据库连接层
- 查询构造层
- 应用层
来看一下每一层有哪些东西,分别对应文档的哪一部分:
数据库连接层
数据库连接层是整个数据库组件依赖的基础,这个不言而喻,但是这部分实际上从 文档 都能够看得出,本身更多是基于 PDO的封装,在此基础上提供了以下几个主要功能:
- 更为直观易用的事务
- 读写分离功能
- 多种数据库驱动兼容和切换
- 数据库事件
这一部分的功能可以通过 Facade 快捷调用(DB 类),文档已有说明,很明显,只要是使用过 PDO或者 MySQLi 的都能够快速上手使用参数绑定和 SQL 预处理功能。为了便于事件处理,这一部分对增删改查四个操作每一个都封装了一个方法,实际上调用方法一致(都是封装的 PDO 和 PDOStatement 类的方法),仅产生的结果类型有所区别。
这一层很底层,对于需要直接手写 SQL 操作数据库的人可以通过这一层访问,大多数情况下我们不会直接使用(不过事务很常用,我们会在后面的文章讲到)。需要注意的是,作为底层,意味着数据库组件后面所有的功能都是利用这一层实现的,因此这一层务必需要有一个了解。
了解 PDO 很重要,现代框架数据库部分基本是基于 PDO实现的。若是作为一名使用到 PHP 5.3 以后版本的 PHPer,连 PDO 都未曾使用甚至都不曾了解的,着实应当面壁,要知道 PDO 可是从 PHP 5.1 以后就已经是一个自带扩展,随 PHP 一同发布。
这一部分不会单独成文介绍,而是会随着下面这一部分,在下一篇文章中同时给出讲述。
查询构造层
查询构造层由 查询构造器和 (语法)生成器组成,是应用层和底层沟通的桥梁,其提供了流畅的访问接口,使得开发者可以以务必优雅的形式创建查询。虽然现代框架都提供了此类功能,但像 Laravel 这种利用很多 PHP 优秀特性来实现的,很少很少。
你可以通过这样的方式查询:
<?php$query = DB::table('users')->where('score', '>', 0) ->where(function (Builder $query) { $query->where('code', 'foo') ->orWhere('name', 'like', 'Anvi%'); })->skip(1) ->take(5) ->get();
最终会生成这样的 SQL:
SELECT * FROM users WHERE score > 0 AND (code = 'foo' OR 'name' LIKE 'Anvi%') OFFSET 1 LIMIT 5;
可以看到,查询构造层的查询构造器提供了十分直观的访问方式,这种方式使得构建 SQL 语句的错误概率大大降低,而且由于是通过方法访问,我们很容易对某一类查询方式进行封装(这个功能会在后文提到),以提高开发效率。
要时刻记住,所使用的 where 或 groupBy 这类方法,全部是查询构造器提供的方法,要在开发中明确这一点,哪一些方法是由哪一层、哪一个类的实例对象提供的,这样有助于避免不必要的错误,这一点我会在 Eloqent 的那一篇文章中着重讲。
查询构造器提供了优雅的访问方法,而最终输出 SQL 语句的则是(语法)生成器,他会根据当前所选的数据库驱动生成对应的 SQL 语句,最后返回给查询构造器,组合好用于绑定的参数,调用数据库连接层返回查询结果。
实际上,查询构造器在数据库组件有两个,一个是基础的原生查询构造器,是查询构造层提供的,还有个则是 Eloqent ORM 再次封装的版本,提供了更为高级的关联查询方法,这个会在后续着重讲解。
应用层
这一层就是我们长期使用的部分了,这一层包含了三个大组件: Eloquent ORM、 Migration、 Schema。
这三个皆是基于查询构造层实现的,Eloquent 出场率最高,当然后两个也很重要,分别是数据迁移和结构生成器,而数据迁移组件和结构生成器作为 最佳组件 CP往往成双成对的出现,对这两位我会单独开篇介绍的。
Eloquent 作为最最重要的部分,戏份也最多,我将分为几个篇章来介绍:
- 模型与数据库(一些思想上的东西)
- Eloquent ORM 基础 (讲解 Laravel 的模型,Eloquent 基础,集合)
- Eloquent ORM 高级运用 (可复用查询封装,事件的运用,Getter 与 Setter)
- 关联查询(各种关联模型的运用实例,关联查询各种问题,由于内容很多,将会分为两篇来讲)
关于数据迁移和结构生成器则会在一篇内介绍。
由于数据库这一块内容非常之多,我需要慢慢整理很多东西,水平原因,期间不可避免会出现很多纰漏,也希望各路大神予以批评和指正。
作为开篇,即是作为刚要给我补完的方向,亦是一个引导内容,因此在后续文章发布过程中会不可避免的发生些许变动,所以也请各位关注的朋友多多留意~

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

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.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
