PHP code example of xuey490 / database
1. Go to this page and download the library: Download xuey490/database library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
xuey490 / database example snippets
use Framework\Database\DatabaseFactory;
// 假设已配置好 logger 和 config
// 切换驱动: 'laravelORM' (Laravel) 或 'think' (ThinkPHP)
$driverType = 'laravelORM';
$db = new DatabaseFactory($config, $driverType, $logger);
// 获取 user 表的操作对象
$query = $db->make('user');
// 通用逻辑:查找状态为1,年龄大于18,按ID倒序,取前10条
if ($driverType === 'laravelORM') {
// === Illuminate (Laravel) 风格 ===
$list = $query->where('status', 1)
->where('age', '>', 18)
->orderBy('id', 'desc') // Laravel 用 orderBy
->limit(10)
->get(); // Laravel 必须调用 get() 结束
// 结果是 Illuminate\Support\Collection
$list->each(function($item) {
echo $item->username; // 对象方式访问 (配置 fetch mode 后) 或 数组方式
});
} else {
// === thinkORM 风格 ===
$list = $query->where('status', 1)
->where('age', '>', 18)
->order('id', 'desc') // ThinkPHP 用 order
->limit(10)
->select(); // ThinkPHP 必须调用 select() 结束
// 结果是 think\Collection
$list->each(function($item) {
echo $item['username']; // 默认是数组方式访问
});
}
use App\Model\User;
// 工厂实例化模型 (等价于 new User)
$userModel = $db(User::class);
// === 插入数据 (Create) ===
// 两种 ORM 这里语法极其相似
$userModel->username = 'xuey863toy';
$userModel->email = '[email protected] ';
$userModel->save();
// 或者使用 create 方法 (需注意 fillable/allowField 配置)
// User::create([...]);
// === 修改数据 (Update) ===
// 假设我们要更新刚插入的数据
// 注意:工厂返回的是空模型,我们需要先查询出来
if ($driverType === 'eloquent') {
$user = $userModel->where('username', 'xuey863toy')->first();
if ($user) {
$user->email = '[email protected] ';
$user->save();
}
// 批量更新
$userModel->where('status', 0)->update(['status' => 1]);
} else {
// thinkORM
$user = $userModel->where('username', 'xuey863toy')->find();
if ($user) {
$user->email = '[email protected] ';
$user->save();
}
// 批量更新
$userModel->where('status', 0)->update(['status' => 1]);
}
$query = $db->make('orders');
if ($driverType === 'eloquent') {
// 查询每个用户的订单总金额
$result = $query->selectRaw('user_id, sum(amount) as total')
->groupBy('user_id')
->having('total', '>', 100)
->get();
// 统计总数
$count = $db->make('users')->count();
} else {
// ThinkORM
$result = $query->field('user_id, sum(amount) as total')
->group('user_id')
->having('total', '>', 100)
->select();
// 统计总数
$count = $db->make('users')->count();
}
$pageSize = 20;
if ($driverType === 'laravelORM') {
// 返回 Illuminate\Pagination\LengthAwarePaginator
$list = $db->make('user')->paginate($pageSize);
// 获取数据
$items = $list->items();
// 获取总页数
$lastPage = $list->lastPage();
} else {
// 返回 think\Paginator
$list = $db->make('user')->paginate($pageSize);
// 获取数据 (ThinkPHP 分页对象可以直接当迭代器用)
foreach ($list as $item) {
// ...
}
// 获取总数
$total = $list->total();
}
// 按条件删除
$db->make('user')->where('id', 1)->delete();
// 清空表 (慎用)
// Eloquent: truncate()
// Think: query('TRUNCATE TABLE user') 或 Db::execute
// 引入必要的 Facade 或 Manager
use Illuminate\Database\Capsule\Manager as Capsule;
use think\facade\Db as ThinkDb;
try {
if ($driverType === 'laravelORM') {
// === Eloquent 事务 ===
Capsule::beginTransaction();
try {
$db->make('user')->where('id', 1)->update(['money' => 0]);
$db->make('log')->insert(['msg' => 'User 1 cleared']);
Capsule::commit();
} catch (\Throwable $e) {
Capsule::rollBack();
throw $e;
}
// 或者使用闭包方式 (推荐)
Capsule::transaction(function () use ($db) {
$db->make('user')->insert(['name' => 'A']);
$db->make('user')->insert(['name' => 'B']);
});
} else {
// === ThinkORM 事务 ===
ThinkDb::startTrans();
try {
$db->make('user')->where('id', 1)->update(['money' => 0]);
$db->make('log')->insert(['msg' => 'User 1 cleared']);
ThinkDb::commit();
} catch (\Throwable $e) {
ThinkDb::rollback();
throw $e;
}
// 或者使用闭包
ThinkDb::transaction(function () use ($db) {
$db->make('user')->insert(['name' => 'A']);
});
}
} catch (\Exception $e) {
echo "事务回滚: " . $e->getMessage();
}