mavi/dbmanager

仓库表的经理。

v1.0.1 2023-07-19 13:35 UTC

This package is auto-updated.

Last update: 2024-09-19 16:24:56 UTC


README

仓库表的经理。
管理器使用PDO(PHP默认启用PDO)。
使用PHP 8.1。

初始化

$dbManager = new DBManager('host', 'db', 'user', 'password');

选择数据

$result = $dbManager->table('users')
                    ->select('users.id, users.name, users.phone')
              // or ->select(['users.id', 'users.name', 'users.phone'])
                    ->where('users.name LIKE ? AND users.id > ?', 'Ja%', 1)
              // or ->where(['users.name LIKE ?', 'users.id > ?'], 'Ja%', 1)
                    ->orderBy('users.name DESC, users.id ASC')
              // or ->orderBy(['users.name DESC', 'users.id ASC'])
                    ->limit(2, 0)
                    ->rightJoin('orders')
                        ->on('users.id = orders.user_id')
                        ->select('price, date')
                        ->endJoin($dbManager)
                    ->fetchAll();

连接表

表可以组合连接

->innerJoin('orders')
    ->on('user.id = orders.id_uzivatele')
    ->select('orders.products, orders.date')
    ->innerJoin('products')
        ->on('order.product_id = product.id')
        ->select('price, vat')
->endJoin($dbManager)

连接函数

->innerJoin(...)
->leftJoin(...)
->rightJoin(...)
->fullJoin(...)

获取数据

->fetchSingle(); // Returns single value

$result = $dbManager->table('users')->select('id')->where(...)->fetchSingle(); // Returns 'id'
$result = $dbManager->table('users')->select('id, name, phone')->where(...)->fetchSingle(); // Returns 'id'
$result = $dbManager->table('users')->select('id, name, phone')->where(...)->fetchSingle(1); // Returns 'name'
$result = $dbManager->table('users')->select('id, name, phone')->where(...)->fetchSingle(2); // Returns 'phone'

->fetch(); // Returns single row as array
->fetchAll(); // Returns array of rows with values as associative array
->fetchPairs(); // Returns rows associated with unique key, values in a rows are associative array
    /*
     * fetchPairs example:
     * [
     *   2 => [id => 2, name => ... ]
     *   5 => [id => 5, name => ...]
     * ]
     */

缓存结果

结果可以缓存。如果执行相同的查询,DBManager将加载缓存的结果。

$dbManager->enableCashing($numberOfMaxCachedResults);
  • 默认的最大缓存结果数是20。
  • 如果达到限制,则移除第一个缓存结果并将结果移位。
  • 对于记录众多的表,缓存是有效的。

插入数据

$dbManager->beginTransaction();

try {
   $id = $dbManager->table('users')->insert(['name' => 'Karl', 'email' => 'karl@example.com'])->getId();
   $dbManager->table('orders')->insert(['user_id' => $id, 'price' => 1000, 'currency' => 'CZK', 'date%sql' => 'NOW()']);
   $dbManager->commit();

} catch (\Exception $e) {
   $dbManager->rollback();
}

更新数据

更新以Kar*开头的用户电话号码,出生日期为1991年3月2日。

$dbManager->table('users')->where('name LIKE ? AND birth_date = ?', 'Kar%', '1991-02-03')->update(['phone' => '+420 555 555 555']);
  • 'Kar%' - 以'Kar'开头的字符串。
  • '%arl' - 以'arl'结尾的字符串。
  • '%ar%' - 包含'ar'的字符串。