search
HomeBackend DevelopmentPHP Tutoriallaravel 学习笔记 —— 数据和模型起步篇

自上一篇 《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)
  • 关联查询(各种关联模型的运用实例,关联查询各种问题,由于内容很多,将会分为两篇来讲)

关于数据迁移和结构生成器则会在一篇内介绍。

由于数据库这一块内容非常之多,我需要慢慢整理很多东西,水平原因,期间不可避免会出现很多纰漏,也希望各路大神予以批评和指正。

作为开篇,即是作为刚要给我补完的方向,亦是一个引导内容,因此在后续文章发布过程中会不可避免的发生些许变动,所以也请各位关注的朋友多多留意~

Statement
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
11 Best PHP URL Shortener Scripts (Free and Premium)11 Best PHP URL Shortener Scripts (Free and Premium)Mar 03, 2025 am 10:49 AM

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Introduction to the Instagram APIIntroduction to the Instagram APIMar 02, 2025 am 09:32 AM

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Working with Flash Session Data in LaravelWorking with Flash Session Data in LaravelMar 12, 2025 pm 05:08 PM

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

Simplified HTTP Response Mocking in Laravel TestsSimplified HTTP Response Mocking in Laravel TestsMar 12, 2025 pm 05:09 PM

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

Build a React App With a Laravel Back End: Part 2, ReactBuild a React App With a Laravel Back End: Part 2, ReactMar 04, 2025 am 09:33 AM

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

cURL in PHP: How to Use the PHP cURL Extension in REST APIscURL in PHP: How to Use the PHP cURL Extension in REST APIsMar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

12 Best PHP Chat Scripts on CodeCanyon12 Best PHP Chat Scripts on CodeCanyonMar 13, 2025 pm 12:08 PM

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

Announcement of 2025 PHP Situation SurveyAnnouncement of 2025 PHP Situation SurveyMar 03, 2025 pm 04:20 PM

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio

See all articles

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!