aymanelarian/import-query-generator-pg

一个高效的Postgres查询生成器,用于批量资源导入,可以区分新记录和需要更新的记录。

v1.3 2020-07-25 12:03 UTC

This package is not auto-updated.

Last update: 2024-09-30 07:42:17 UTC


README

一个高效的查询生成器,用于批量资源导入,可以区分新记录和需要更新的记录。这个库使用了Postgree的ON CONFLICT DO UPDATE特性。

它是由kfirba/import-query-generator分支而来,并针对Postgree SQL进行了调整。

前言

我强烈建议您至少浏览一下我的关于这个库的博客,以更好地了解这个库。

安装

您可以使用Composer将这个库作为本地、项目级依赖添加到您的项目中。

composer require AymanElarian/import-query-generator-pg

使用方法

use AymanElarian\QueryGenerator;

$table = 'users';
$data = [
    ['name' => 'John', 'email' => 'john@example.com', 'password' => 'hashed_password', 'created_at' => date('Y-m-d'), 'updated_at' => date('Y-m-d')],
    ['name' => 'Jane', 'email' => 'jane@example.com', 'password' => 'hashed_password', 'created_at' => date('Y-m-d'), 'updated_at' => date('Y-m-d')],
    ['name' => 'Susy', 'email' => 'susy@example.com', 'password' => 'hashed_password', 'created_at' => date('Y-m-d'), 'updated_at' => date('Y-m-d')],
];
$excludedColumnsFromUpdate = ['password', 'created_at'];

$queryObject = (new QueryGenerator)->generate($table, $data, $excludedColumnsFromUpdate);

$queryObject->getQuery();
// -> "insert into `users` (`name`,`email`,`password`,`created_at`,`updated_at`) values (?,?,?,?,?),(?,?,?,?,?),(?,?,?,?,?) on duplicate key update `name`=VALUES(`name`),`email`=VALUES(`email`),`updated_at`=VALUES(`updated_at`)"

$queryObject->getBindings();
// -> ['John', 'john@example.com', 'hashed_password', '2018-01-12', '2018-01-12', 'Jane', 'jane@example.com', 'hashed_password', '2018-01-12', '2018-01-12', 'Susy', 'Susy@example.com', 'hashed_password', '2018-01-12', '2018-01-12']

如您所注意到的,生成器默认使用column=VALUES(column),因为这通常是我们尝试批量导入数据时使用的。需要其他行为吗?您可以提交一个PR,或者创建一个issue,我们可以讨论它 🤓。

许可证

此软件包是开源软件,根据MIT许可证授权。