PHP 7 的流畅查询构建器和基于 ActiveRecord 的 ORM

v0.1.2 2019-11-08 19:35 UTC

This package is auto-updated.

Last update: 2024-09-26 01:12:51 UTC


README

基于 ActiveRecord 的 PHP 7 ORM,灵感来自 Eloquent 和 Yii2 ORM。

入门指南

创建一个新的 PDO 实例,并将其传递给 Query

use Dynamo\ORM\Query;
....
$pdo = new \PDO('mysql:dbname=goldoni;host=localhost;charset=utf8', 'root', 'root');
$query = (new Query($pdo))

或者更好,全局设置 PDO

Query::setPdo($pdo);
....
$query = (new Query()) // this will use the static PDO instance.

查询构建器

流畅直观的查询构建器

$users = (new Query)
  ->select('*') // This is the default select
  ->from('users')
  ->where([
    'role' => 'ADMIN', // translates to "role = ?", where "?" will be securely replaced by the PDO layer
    'age > $minAge', // insecure! $minAge is not verified! However, we allow this form for convenience
    [ 'age', '<=', $maxAge ], // better
  ], false) // false "OR's" all the previous conditions. Default is true, which will "AND" all the conditions. 
  ->all(); // Fetches all the results

安装

composer require dynamonet/orm

定义模型

您的数据库模型类应该扩展 Dynamo\ORM\ActiveModel

<?php

namespace MyApp;

use Dynamo\ORM\ActiveModel;

class User extends ActiveModel
{
    //
}

按照惯例,类的 "snake case" 名称将被用作表名。如果您想指定不同的表名,可以通过简单地重写静态的 "getTableName" 方法来实现

<?php

namespace MyApp;

use Dynamo\ORM\ActiveModel;

class User extends ActiveModel
{
    public static function getTableName()
    {
        return 'my_users_table';
    }
}

关系

定义关系的方式与在 Yii2 的 ORM 或 Eloquent 中相同。

一对一关系

(进行中)