1owe1 / query-box
SQL不可变查询构建器
1.2.2
2023-08-17 13:04 UTC
Requires
- php: >=8.1
- ext-pdo: *
- monolog/monolog: ^3.0
Requires (Dev)
- phpstan/phpstan: ^1.7
- phpunit/phpunit: ^9.5
README
描述
实际功能
- 选择、插入、更新、删除;
- Where、连接(内部、左、右)、限制、排序;
- 子查询;
- 简单的迁移工具。
设置
- 使用Composer安装包
composer reuire 1owe1/query-box
- 直接在您的$_ENV中设置数据库连接参数(如bootstrap操作)或使用.env解析器
// PHP version // required params $_ENV["DB_USER"] = "default_user"; $_ENV["DB_PASS"] = "password"; $_ENV["DB_NAME"] = "default"; // optional params $_ENV["DB_TYPE"] = "mysql"; // or "pgsql" ("mysql" by default) $_ENV["DB_HOST"] = "127.0.0.1"; // localhost by default $_ENV["DB_PORT"] = "3306"; // 3306 by default // extra params $_ENV["LOG_QUERY_RESULTS"] = "true" // false by default $_ENV["LOG_PATH"] = "/my/log/path" // by default use stdOut $_ENV["DB_IMMUTABLE"] = "false" // manage type of connection with db (persistence or immutable)
# .ENV version # required params DB_USER="default_user"; DB_PASS="password"; DB_NAME="default"; # optional params DB_TYPE="mysql"; # or "pgsql" ("mysql" by default) DB_HOST="127.0.0.1"; # localhost by default DB_PORT="3306"; # 3306 by default # extra params LOG_QUERY_RESULTS="true" # false by default LOG_PATH="/my/log/path" # by default use stdOut DB_IMMUTABLE="false" # manage type of connection with db (persistence or immutable)
- 创建您的第一个模型(或使用QueryBuilder::table('my_table'))
<?php declare(strict_types=1) namespace App\Models; use QueryBox\QueryBuilder\QueryBuilder; // interface for migration use QueryBox\Migration\MigrateAble; class MyTable extends QueryBuilder implements MigrateAble { // MigrateAble implement static function migrationParams(): array { return [ "fields" => [ "id" => "BIGINT NO NULL", "foreign_id" => "INT NOT NULL", "field" => "CHAR(10)", ], "foreign" { "foreign_id" => [ForeignTable::class, "id"], } ] } }
迁移示例
<?php declare(strict_types=1); use QueryBox\Migration\MetaTable; use QueryBox\DBFacade; use App\Models\MyTable; MetaTable::migrateFromMigrateAble(DBFacade::getDBInstance(), MyTable::class);
用法
<?php declare(strict_types=1); use App\Models\MyTable; use App\Models\AnotherTable; $queryResult = MyTable::select(["id", "field"]) ->leftJoin([AnotherTable::table()], ["foreign_id", "id"]) ->where("field", "LIKE", "something") ->orderBy("id") ->limit(1) ->save(); var_dump($queryResult->fetchAll());
配置
应用期望以下全局变量
- 调试选项
- $_ENV['LOG_QUERY_RESULTS'] (布尔值,默认为false) - 将原始查询记录到日志文件中(如果需要,则需要日志路径否则将输出到标准输出);
- $_ENV['LOG_PATH'] (字符串) - 日志文件的路径;
- 数据库连接
- $_ENV['DB_TYPE'] (mysql/pgsql,默认为mysql) - 数据库类型(目前只支持mysql和pgsql);
- *$_ENV['DB_NAME'] (必需) - 数据库名;
- $_ENV['DB_HOST'] (默认localhost) - 数据库主机;
- $_ENV['DB_PORT'] (默认3306) - 数据库端口;
- *$_ENV['DB_USER'] (必需) - 数据库用户名或角色;
- *$_ENV['DB_PASS'] (必需) - 数据库密码。
测试
在./test目录中定义了测试(QueryBox\Tests\命名空间),使用'./vendor/bin/phpunit'。
您还可以使用phpstan,通过'./vendor/bin/phpstan'(默认级别为9)。
示例
您还可以在./example目录中找到一些示例。