wtframework / dbal
这是什么框架?!DBAL
v0.3.0
2024-09-14 09:24 UTC
Requires
- php: ^8.2
- wtframework/config: ^0.1
- wtframework/sql: ^0.3
Requires (Dev)
- pestphp/pest: ^3.0
README
此库通过PDO包装扩展了SQL库。
ORM库扩展此库以提供对象关系映射。
安装
composer require wtframework/dbal
文档
配置
MySQL
MySQL
SQLite
PostgreSQL
SQL Server
执行未准备好的语句
使用unprepared
方法执行未准备好的语句。
$response = DB::unprepared("SELECT * FROM users"); $response = DB::select()->from("users")->unprepared();
准备语句
使用prepare
方法准备语句。
$response = DB::prepare("SELECT * FROM users WHERE user_id = ?"); $response = DB::select()->from("users")->where("user_id", "?")->prepare();
使用bind
方法绑定任何参数。
$response->bind(1);
使用execute
方法执行语句
$response->execute();
准备和执行语句
使用execute
方法准备和执行语句。
$response = DB::execute("SELECT * FROM users WHERE user_id = ?", 1); $response = DB::select()->from("users")->where("user_id", 1)->execute();
当使用语句构建器时,您还可以通过将其作为函数调用来执行语句。
DB::insert()->into("users")();
检索结果集
使用get
方法返回单行结果集。
DB::get("SELECT * FROM users WHERE user_id = ?", 1); DB::select()->from("users")->where("user_id", 1)->get();
您还可以在任何响应上使用get
方法。
$response->get();
使用all
方法以数组形式返回结果集。
DB::all("SELECT * FROM users"); DB::select()->from("users")->all();
您还可以在任何响应上使用all
方法。
$response->all();
杂项
在执行语句后使用insertID
方法返回最后插入的ID。
DB::insert()->into("users")->execute(); DB::insertID();
在执行语句后使用affectedRows
方法返回插入或更新的行数。
$response = DB::update()->table("users")->set('active', 1)->execute(); $response->affectedRows();
事务
使用beginTransaction
、commit
和rollback
方法执行事务。
DB::beginTransaction(); DB::commit(); DB::rollBack();
您还可以使用transaction
方法来自动开始一个事务,该事务在成功时提交或失败时回滚。
DB::transaction(function () { DB::insert()->into("users")->execute(); // ... });
使用非默认数据库连接
如果您有多个连接并希望使用非默认连接,则可以使用传递连接名称的connection
方法。这将返回一个WTFramework\DBAL\Connection
实例,它具有与上述文档中相同的函数。
$response = DB::connection("mirror")->select()->from("users")->where("user_id", 1)->get();
语句
这些静态方法中的每一个都会返回用于生成SQL语句字符串的流畅接口。有关更多信息,请参阅SQL库。
use WTFramework\DBAL\DB; DB::select(); DB::insert(); DB::replace(); DB::update(); DB::delete(); DB::truncate(); DB::create(); DB::alter(); DB::drop(); DB::createIndex($name); DB::dropIndex($name);
服务
这些静态方法中的每一个都会返回一个服务类。有关更多信息,请参阅SQL库。
DB::bind($value); DB::column($name); DB::constraint($name); DB::cte($name, $stmt); DB::index($name); DB::outfile($path); DB::partition($name); DB::raw($string); DB::subpartition($name); DB::subquery($stmt); DB::table($name); DB::upsert(); DB::window($name);
扩展库
要扩展库,您可以使用静态macro
方法,传递新的方法名称和要调用的闭包。这对于静态和非静态方法都适用。这在DB
、Connection
和Response
类上都是可用的。
use WTFramework\DB\DB; DB::macro('count', function (string $table) { return static::select() ->column('COUNT(*) AS counter') ->from($table) ->get() ->counter; });
DB::count('users');