Eloquent 是 Laravel 的 ORM (Object-Relational Mapper)——它使用 Active Record 模式,其中每个数据库表都有一个对应的 Model 类,模型实例代表行。它提供了一种优雅、富有表现力的方式来查询和操作数据库,无需编写 SQL。
定义模型
{
= [, ];
}
模型扩展 Model 并通过命名约定映射到表(User → users)。$fillable 列表控制哪些字段可以批量赋值(一项安全功能)。
// CREATE
$user = User::create(['name' => 'Ann', 'email' => '[email protected]']);
$user = new User; $user->name = 'Bob'; $user->save();
// READ
User::all(); // all rows
User::find(1); // by primary key
User::where('active', true)->get(); // query with conditions
User::where('email', $email)->first(); // first match
// UPDATE
$user->update(['name' => 'New Name']);
$user->name = 'X'; $user->save();
// DELETE
$user->delete();
User::destroy(1);
Eloquent 的流畅、可链式 API 读起来几乎像英文,并为你生成 SQL——常见操作无需原始查询。
User::where('age', '>', 18)
->where('active', true)
->orderBy('name')
->limit(10)
->get(); // chainable query building
User::where('role', 'admin')->count();
User::where('email', $e)->exists();
class Post extends Model {
public function author() { // a relationship
return $this->belongsTo(User::class);
}
public function getExcerptAttribute() { // an accessor (computed attribute)
return Str::limit($this->body, 100);
}
}
$post->author; // the related User
$post->excerpt; // computed attribute
Eloquent 是 Laravel 的核心——它是应用程序与数据库交互的方式,其优雅的 Active Record 设计是该框架最受推崇的特性之一,因此掌握它对任何 Laravel 开发都是必不可少的。
理解如何定义模型(通过约定映射到表)、执行 CRUD 操作以及使用流畅、可链式构建器进行查询是日常的、基础性的知识,因为数据访问是大多数应用程序的核心。
Eloquent 的富有表现力、可读的 API(User::where(...)->orderBy(...)->get())让你在干净的 PHP 中使用数据库,无需编写 SQL,大大提高了生产力和可读性。
模型不仅仅是数据容器——它们定义了 relationships(连接相关表)并可以拥有 accessors/mutators(计算属性)和业务逻辑,使它们成为丰富的领域对象。
了解 $fillable 批量赋值保护(一项安全考虑)也很重要。
由于 Eloquent 是 Laravel 应用程序读写数据的方式——并且出现在几乎每个 Laravel 应用程序中——掌握模型和 Eloquent 的查询 API 是基础性的、必知的材料,是有效 Laravel 开发的基础。