您的当前位置:首页>全部文章>文章详情

【Webman+MySQL教程四】ORM 模型与增删改查实战

果子发表于:2026-10-04 14:10:57浏览:2次TAG: #webman #PHP #MySql #ORM

本篇目标

用 webman/database 提供的 Eloquent 模型封装 student 表,掌握常用的查询构建与增删改查写法,避免到处手写 SQL。

一、定义模型

新建 app/model/Student.php:

<?php
namespace app\model;

use Illuminate\\Database\\Eloquent\\Model;

class Student extends Model
{
    protected $table = 'student';        // 表名,默认是类名复数,这里显式指定
    protected $primaryKey = 'id';
    public $timestamps = false;          // 我们的表没有 updated_at

    protected $guarded = [];             // 允许批量赋值(演示用,正式项目建议 fillable 白名单)
}

二、查询(Query)

use app\\model\\Student;

// 全表
$all = Student::all();

// 条件
$list = Student::where('class_name', '党校1班')
    ->where('score', '>=', 80)
    ->orderByDesc('score')
    ->get();

// 只取部分列 / 单条
$one = Student::where('id', 1)->first();
$name = Student::where('id', 2)->value('name');

// 计数 / 聚合
$total = Student::count();
$avg   = Student::avg('score');

// 分页(返回 paginate 对象,带 meta 信息)
$page = Student::paginate(10);

三、新增(Create)

// 方式 1:create 批量赋值
$stu = Student::create([
    'name' => '赵六',
    'class_name' => '党校2班',
    'score' => 81.5,
]);
$newId = $stu->id;   // 自增主键直接拿

// 方式 2:new + save
$stu = new Student();
$stu->name = '钱七';
$stu->class_name = '党校3班';
$stu->score = 90;
$stu->save();

四、修改(Update)

// 单条
$stu = Student::find(4);
$stu->score = 95.0;
$stu->save();

// 批量:把党校1班所有成绩 +2
Student::where('class_name', '党校1班')
    ->increment('score', 2);

// 按条件更新指定字段
Student::where('id', 1)->update(['name' => '张三丰']);

五、删除(Delete)

// 单条
Student::find(5)->delete();

// 批量
Student::where('score', '<', 60)->delete();

六、查询构建器(不建模型也能用)

临时表或不想建模型时,直接用 support\\Db:

use support\\Db;

$rows = Db::table('student')
    ->where('class_name', '党校2班')
    ->select('name', 'score')
    ->get();

Db::table('student')->insert([
    'name' => '孙八', 'class_name' => '党校1班', 'score' => 77.5,
]);

七、原生 SQL

$rows = Db::select('SELECT class_name, AVG(score) avg_score FROM student GROUP BY class_name');
$affected = Db::statement('UPDATE student SET score = 100 WHERE id = ?', [1]);

参数务必用占位符 ?,不要拼接字符串,防 SQL 注入。

小结

模型定义 + 常用 CRUD 到这里已经够用。最后一篇(第 5 篇)把这些组装成一个完整的 RESTful JSON 接口:统一返回结构、参数校验、异常处理。