axisstudios / db-record
管理数据库记录。此库是 SoloProyectos PHP API 的一部分。
Requires
- php: >=5.5.0
- soloproyectos-php/array: ~1.0
- soloproyectos-php/db: ~1.1
- soloproyectos-php/text: ~1.0
README
介绍
DbRecord
是一个库,允许我们无需手动执行 SQL 语句来操作数据库。与其他类似库不同,DbRecord 允许我们同时操作多个表,从而实现更简洁、更清晰的代码。
安装
此软件包由 composer 软件包管理器提供。只需创建一个 composer.json
文件,并在同一目录下执行以下命令
composer install
有关更多信息,请参阅 基本用法。
数据库要求
此库可以操作任何 MySQL 数据库,唯一条件是每个表 必须 有一个由单个自增列组成的复合主键。默认情况下,主键名为 ID
,但您可以从构造函数中更改它。
基本示例:insert()、update()、select() 和 delete()
我们使用 DbRecordTable
类来执行基本操作。
插入记录
要插入记录,请从构造函数中省略 id
参数
// insert a record, as the 'id' parameter is not present $t = new DbRecordTable($db, "table0"); $id = $t->insert(["title" => "New title", "created_at" => date("Y-m-d H:i:s")]); echo "Inserted record ID: $id";
更新记录
更新 ID=1 的记录
$t = new DbRecordTable($db, "table0"); $t->update(["title" => "New title", "created_at" => date("Y-m-d H:i:s")], 1);
插入/更新记录
您可以在同一行中插入或更新记录。例如
$t = new DbRecordTable($db, "table0"); // if $recordId is null, insert a new record and returns the id, // otherwise update the current record $recordId = $t->save(["title" => "New title", "created_at" => date("Y-m-d H:i:s")], $recordId); echo $recordId;
选择记录
选择 ID=1 的记录
$t = new DbRecordTable($db, "table0"); list($title, $createdAt) = $t->select(["title", "created_at"], 1); echo "title: $title, Created at: $createdAt";
删除记录
删除 ID=1 的记录
$t = new DbRecordTable($db, "table0"); $t->delete(1);
有关更复杂的示例,请参阅 test1.php。
通用示例:同时访问多个表
假设我们有一个主表 (table0
) 和三个副表 (table1
、table2
和 table3
)。三个表通过列 table1_id
、table2_id
和 table3_id
与主表 'left joined'。即:
我们可以在同时操作表而不是逐个操作。以下示例选择记录 (ID = 1) 并在 table1
、table2
和 table3
上更新或插入记录
// the following example updates table0, table1, table2 and table3 at the same time $t = new DbRecordTable($db, "table0"); $t->update( [ "title" => "My title", "created_at" => date("Y-m-d H:i:s"), "table1.title" => "Title 1", "table2.title" => "Title 2", "table3.title" => "Title 3" ], 1 );
以下示例选择记录 (ID = 1) 并同时检索 table0
、table1
、table2
和 table3
的列
$t = new DbRecordTable($db, "table0"); list($title, $createdAt, $t1Title, $t2Title, $t3Title) = $t->select( [ "title", "created_at", "table1.title", "table2.title", "table3.title" ], 1 ); echo "title: $title, created_at: $createdAt, table1.title: $t1Title, table2.title, $t2Title, table3.title, $t3Title";
有关更复杂的示例,请参阅 test2.php。
列路径表达式
在前面的示例中,我们通过以下表达式访问 table1
的 title
列:table1.title
。通用格式如下
table1[id = table0_id].title
我们可以省略 id
和 table0_id
,因为它们默认会使用。所以前面的表达式可以简化如下
table1.title
让我们想象一个更复杂的示例。假设 table2
依赖于 table1
,而 table1
同时也依赖于 table0
。即
在这种情况下,我们使用以下代码来访问 table1
和 table2
的列
$t = DbRecordTable($db, "table0"); list($title, $t1Title, $t2Title) = $t->select( [ "title", "table1.title", "table2[table1.table2_id].title" ], 1 );
前面的表达式是通用表达式的简化版本
table1[id = table1_id].title
table2[id = table1.table2_id].title
我们可以省略 id
和 <table>_id
,因为它们默认会使用。