softwarepunt /instarecord
MySQL 数据库 ORM 层的 ActiveRecord
v0.5.1
2024-06-28 13:22 UTC
Requires
- php: >=8.1
- ext-json: *
- ext-pdo: *
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-08-28 13:47:13 UTC
README
✨ 一款高效的 PHP ORM。
Instarecord 使你在 PHP 中与 MySQL 数据库交互变得超级简单和有趣。它快速直观,并包含许多可选功能,让你的生活更轻松。
介绍
🧙♂️ 使用类型变量定义模型,Instarecord 会自动处理其余部分!
<?php class User extends Model { public int $id; public string $email; public ?string $name; } $user = new User(); $user->email = "bob@web.net"; $user->save(); echo "Created user #{$user->id}!";
特性
🗺️ 对象映射
将模型定义为具有类型属性的纯 PHP 类,就像使用常规对象一样。
📦 简单 CRUD
在模型上使用直观的对象化 CRUD 操作(创建、读取、更新和删除)。
🔎 查询构建器
使用查询构建器快速构建和运行更复杂的查询,并使用预处理语句执行。
🤝 关系
在模型之间设置关系,并轻松以优化方式加载。
✅ 验证
为模型属性添加约束,并以用户友好的错误消息进行验证。
快速入门
安装
使用 Composer 将 Instarecord 添加到您的项目中
composer require softwarepunt/instarecord
配置
传递自己的 DatabaseConfig
或修改默认配置
<?php use SoftwarePunt\Instarecord\Instarecord; $config = Instarecord::config(); $config->charset = "utf8mb4"; $config->unix_socket = "/var/run/mysqld/mysqld.sock"; $config->username = "my_user"; $config->password = "my_password"; $config->database = "my_database"; $config->timezone = "UTC";
使用模型
通过创建具有公共属性的普通类并扩展 Model
来定义模型
<?php use SoftwarePunt\Instarecord\Model; class Car extends Model { public int $id; public string $make; public string $model; public int $year; }
现在您可以轻松地创建、读取、更新和删除记录
$car = new Car(); $car->make = "Toyota"; $car->model = "Corolla"; $car->year = 2005; $car->save(); // INSERT INTO cars [..] // Post insert, the primary key (id) is automatically populated $car->year = 2006; $car->save(); // UPDATE cars SET year = 2006 WHERE id = 123 $car->delete(); // DELETE FROM cars WHERE id = 123
运行查询
您可以轻松构建和运行自定义查询,并以各种方式获取结果 - 从原始数据到完整填充的模型。
从模型
$matchingCars = Car::query() ->where('make = ?', 'Toyota') ->andWhere('year > ?', 2000) ->orderBy('year DESC') ->limit(10) ->queryAllModels(); // Car[]
独立使用
$carsPerYear = Instarecord::query() ->select('year, COUNT(*) as count') ->from('cars') ->groupBy('year') ->queryKeyValueArray(); // [2005 => 10, 2006 => 5, ..]