PHP 简单查询构建器

v2.1 2020-07-13 13:16 UTC

This package is auto-updated.

Last update: 2024-09-13 23:07:50 UTC


README

DB 类是 PHP 中的一个简单查询构建器类,它基于 PDO,需要 php 版本 > 7.1。

用法

首先加载您的数据库配置

\Odb\DB::loadConfig("DBConf.php");

数据库配置如下所示

return [
    'default' => [     // default must exists
        'driver' => 'mysql',   // pgsql(postgresql)
        'host' => '127.0.0.1',
        'port' => '3306',
        'username' => '',
        'password' => '',
        'dbname' => '',
        'charset' => 'utf8',
        'pconnect' => false,
        'time_out' => 3,
        'prefix' => '',
        'throw_exception' => true
    ]
];

我们使用默认的 "default" 连接,因此需要默认配置。然后您必须按照如下方式实例化类

\Odb\DB::connect()->getDBVersion();

切换其他连接配置

\Odb\DB::connect('default')->query(...)->get();

向表中插入值

插入一条记录

\Odb\DB::table('user')->insert(['name' => 'jack', 'age' => 24]);

插入多条记录

\Odb\DB::table('user')->insert([['name' => 'linda', 'age' => 21], ['name' => 'bob', 'age' => 24]]);

获取插入记录的 ID

$id = \Odb\DB::table('user')->insertGetId(['name' => 'ailan', 'age' => 21]);

限制插入的列

\Odb\DB::table('user')->allow('name', 'age')->insert(['name' => 'jack', 'age' => 24, 'job' => 'programmer']);

要查看已执行的 SQL 查询,请使用 getSQL() 方法,如下所示

echo \Odb\DB::table('user')->buildInsert(['name' => 'jack', 'age' => 24])->getSQL();

输出

'insert into `user` (`name`,`age`) values (?,?)'
echo \Odb\DB::table('user')->buildInsert(['name' => 'jack', 'age' => 24])->getRSql();

输出

'insert into `user` (`name`,`age`) values ('jack', 24)'

更新表值

\Odb\DB::table('user')->where('id', 1)->update(['name' => 'remi']);

SQL 查询

'update `user` set `name`=? where `id`=?'

增加

\Odb\DB::table('scores')->where('id', 10)->increment('score');
\Odb\DB::table('scores')->where('id', '=', 10)->increment('score', 5);
\Odb\DB::table('scores')->where('id', '=', 10)->increment([['score', 1], ['level', 9]]);

减少

\Odb\DB::table('scores')->where('id', '=', 10)->decrement('score');
\Odb\DB::table('scores')->where('id', '=', 10)->decrement('score', 2);
\Odb\DB::table('scores')->where('id', '=', 10)->decrement([['score', 2], ['level', 1]]);

注意

如果没有 WHERE 条件,则不会发生更改

从表中删除值

\Odb\DB::table('logs')->where([['id', '>', 9], ['level', '<', 2]])->delete();

注意

如果没有 WHERE 条件,则不会删除任何内容

选择

$rows = \Odb\DB::table('user')->get();

返回二维数组输出

[
    ['name' => 'jack', 'age' => 21],
    ['name' => 'bob', 'age' => 23]
]

获取一行记录

$user = \Odb\DB::table('user')->first();

返回一维数组

['name' => 'jack', 'age' => 21]

获取记录列表

$userNames = \Odb\DB::table("users")->pluck('username');
$userNames = \Odb\DB::table("users")->pluck('username', 'id');

返回一维数组

['job', 'jack']
[1 => 'job', 2 => 'jack']

获取字段值

echo \Odb\DB::table('users')->where('id', '=', 2)->value('username');  // 'jack'

聚合函数

\Odb\DB::table('user')->max('age');
\Odb\DB::table('user')->min('age');
\Odb\DB::table('user')->sum('age');
\Odb\DB::table('user')->count();
\Odb\DB::table('user')->avg('age');

使用 WHERE

\Odb\DB::table('user')->where('id', 10)->where('level', '=', 5)->get();
\Odb\DB::table('user')->where([['id', '>', 10], ['level', '=', 5]])->orWhere('status', '=', 0)->get();
\Odb\DB::table('user')->where([['id', '>', 10], ['level', '=', 5]])->orWhere('status', '=', 0)
    ->orWhere(function ($query) {
        $query->whereNull('username');
    })->get();

WHERE 函数

whereNull('username');
whereNotNull('username');
whereIn('id', [1, 2, 3]);
whereNotIn('id', [1, 2, 3]);
whereBetween('id', [1, 9]);
whereNotBetween('id', [1, 9]);
whereColumn('id', '>', 'parent_id');
where('`username`=? and `age`>?', ['job', 23]);
where('username', '=', 'job')->where('age', '>', 23);
where([['username', '=', 'job'], ['age', '>', 23]]);
whereRaw('`id`>? and `status`=?', [10, 1]);

使用 SELECT

过滤列

\Odb\DB::table('users')->select('id', 'username', 'age')->get();
\Odb\DB::table('users')->select(['id', 'username', 'age'])->get();
\Odb\DB::table('users')->select(['id', 'username', 'age', 'sum(score) as total'])->get();

使用 JOIN

JOIN 函数

\Odb\DB::table('user as u')->join('article as a', 'u.id', '=', 'a.uid')->select('u.*', 'a.commend')->get();

SQL 查询

'select  `test_u`.`*`,`test_a`.`commend` from `test_user` as `test_u`  inner join `test_article` as `test_a` on `test_u`.id=`test_a`.uid'

您还可以使用 'leftJoin' 和 'rightJoin' 以及原生 SQL

\Odb\DB::table('user')->leftJoin('role', 'user.role_id', '=', 'role.id')->rightJoin('posts', 'uid', '=', 'user.id');
\Odb\DB::table('user')->join('role', 'test_user.role_id=test_role.id and test_role.status>?', [1]);

ORDER BY, GROUP BY...

\Odb\DB::table('user')->orderBy('id', 'desc')->get();
\Odb\DB::table('user')->orderBy('id', 'asc')->get();
\Odb\DB::table('user')->select('count(id) as num')->groupBy('team_id')->having('num', '>', 2)->get();
\Odb\DB::table('user')->select('count(id) as num')->groupBy('team_id')->having('`num`>?', [2])->get();
\Odb\DB::table('user')->limit(2)->get();
\Odb\DB::table('user')->limit(5, 2)->get();

事务

oringfy/DB 提供事务常用 API

\Odb\DB::beginTrans();
\Odb\DB::inTrans();
\Odb\DB::rollBack();
\Odb\DB::commit();

原生 SQL

oringfy/DB 也支持原生 SQL

\Odb\DB::exec('delete from test_user');
\Odb\DB::query('select * from test_user')->get();
\Odb\DB::prepare('select * from test_user where id>?')->execute([10])->get();
\Odb\DB::prepare('update test_user set username=?')->execute(['aiwa'])->rowCount();
\Odb\DB::prepare('insert into test_user (username) values(?)')->execute(['aiwa'])->lastInsertId();
提示

如果您有任何问题,请联系 orinfy@foxmail.com