约 3 分钟阅读
Eloquent ORM 基础
Eloquent 是 Laravel 最引以为傲的核心组件之一。每个数据库表都有一个对应的“模型(Model)”,用于与该表进行直观的数据交互。
定义模型
# 生成模型及其数据库迁移文件
php artisan make:model Flight -m
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
use SoftDeletes;
// 可批量赋值的属性
protected $fillable = [
'name',
'airline',
'departure_time',
'price',
];
// 属性类型自动强转 (Casts)
protected function casts(): array
{
return [
'departure_time' => 'datetime',
'price' => 'decimal:2',
'is_active' => 'boolean',
];
}
}
优雅的数据查询
use App\Models\Flight;
// 获取所有航班
$flights = Flight::all();
// 链式条件查询与排序
$activeFlights = Flight::where('airline', 'Air China')
->where('price', '<', 1000)
->orderBy('departure_time', 'asc')
->take(10)
->get();
// 根据主键获取,未查到则抛出 404 异常
$flight = Flight::findOrFail(1);
// 新增数据
$newFlight = Flight::create([
'name' => 'CA1832',
'airline' => 'Air China',
'price' => 850.00,
]);
// 更新数据
$flight->price = 799.00;
$flight->save();