asko/orm
Requires
- php: >=8.2
- ext-pdo: *
- asko/collection: ^1.0
- crell/fp: ^1.0
Requires (Dev)
- phpstan/phpstan: ^1.11
- phpunit/phpunit: ^11
README
A object relational mapper with a query builder and out of box support for MySQL databases.
安装
composer require asko/orm
设置
首先创建一个基模型类,您的实际数据模型将扩展它,如下所示
use Asko\Orm\BaseModel; use Asko\Orm\Drivers\MysqlDriver; /** * @template T * @extends BaseModel<T> */ class Model extends BaseModel { public function __construct() { parent::__construct(new MysqlDriver( host: "", name: "", user: "", password: "", port: 3006 )); } }
然后您可以创建所有数据模型,如下所示
use Asko\Orm\Column; /** * @extends Model<User> */ class User extends Model { protected static string $_table = "users"; protected static string $_identifier = "id"; #[Column] public int $id; #[Column] public string $name; #[Column] public string $email; }
然后哇,您已经将数据类映射到数据库中的表,全部具有完整的类型支持(与PHPStan配合使用尤其出色)。
注意,$_identifier应与主键列的名称匹配,在上述情况中为id,而$_table应与数据库表名称匹配,自然。这里的其他属性代表表的列,这些将在查询数据时由ORM自动填充,并且必须具有Column属性。
查询
您可以使用ORM中内置的众多查询构建器方法来查询数据。
一个查询示例如下所示
$user = (new User) ->query() ->where('id', '=', 1) ->first();
尽管因为我们使用主键标识符来搜索用户,所以上述查询可以简化为
$user = (new User)->find(1);
所有查询方法
where
过滤结果的where子句。
Usage
(new User)->query()->where('id', '=', 1); // or (new User)->query()->where('id', '>', 1);
andWhere
与where相同,但使用AND运算符。
Usage
(new User)->query()->where('id', '=', 1)->andWhere('email', '=', 'john@smith.com');
orWhere
与where相同,但使用OR运算符。
Usage
(new User)->query()->where('id', '=', 1)->orWhere('email', '=', 'john@smith.com');
orderBy
按列排序结果。
Usage
(new User)->query()->orderBy('id', 'asc');
limit
限制结果数量。
Usage
(new User)->query()->limit(10);
offset
偏移结果。
Usage
(new User)->query()->offset(10);
join
连接另一个表。
Usage
(new User)->query()->join('posts', 'posts.user_id', '=', 'users.id');
leftJoin
使用左连接连接另一个表。
Usage
(new User)->query()->leftJoin('posts', 'posts.user_id', '=', 'users.id');
rightJoin
使用右连接连接另一个表。
Usage
(new User)->query()->rightJoin('posts', 'posts.user_id', '=', 'users.id');
innerJoin
使用内部连接连接另一个表。
Usage
(new User)->query()->innerJoin('posts', 'posts.user_id', '=', 'users.id');
outerJoin
使用外部连接连接另一个表。
Usage
(new User)->query()->outerJoin('posts', 'posts.user_id', '=', 'users.id');
raw
将原始SQL添加到查询中。
Usage
(new User)->query()->raw('WHERE id = ?', [1]);
get
获取所有结果。
Usage
(new User)->query()->get();
first
获取第一个结果。
Usage
(new User)->query()->first();
last
获取最后一个结果。
Usage
(new User)->query()->last();
创建
要在数据库中创建新记录,您可以执行以下操作
$user = new User; $user->name = "John Smith"; $user->email = "john@smith.com" $user->store();
更新
要更新数据库中的记录,您可以执行以下操作
$user = (new User)->find(1); $user->name = "John Doe"; $user->store();
删除
要删除数据库中的记录,您可以执行以下操作
$user = (new User)->find(1); $user->delete();
创建连接驱动程序
ORM已经内置了MySQL驱动程序,但如果您希望扩展ORM以支持其他数据库,您可以通过创建一个新的实现ConnectionDriver接口的驱动程序类来实现,如果您需要由于与MySQL查询构建器的语法差异而构建新的查询构建器,您可以通过创建一个新的实现QueryBuilder接口的查询构建器类来实现。