c24-toys/doctrine-bulk

允许对 Doctrine 实体进行批量操作的简单类(仅支持 mySQL upsert)

4.0.2 2023-03-24 16:08 UTC

This package is auto-updated.

Last update: 2024-09-24 19:08:39 UTC


README

增加了使用 doctrine 模式和 ORM 对象在数据库中批量插入/更新实体或数组的多个 upsert/insert on duplicate(仅限 MySQL)的能力。

INSERT ... ON DUPLICATE KEY UPDATE Statement for ORM objects
    INSERT INTO t1 (a,b,c) VALUES (1,2,3)
    ON DUPLICATE KEY UPDATE c=c+1;

https://dev.mysqlserver.cn/doc/refman/8.0/en/insert-on-duplicate.html

警告:此功能将仅从您的 ORM 对象列表中创建 insert on duplicate SQL 查询

  • 支持的关系/连接类型为 ONE_TO_ONE AND MANY_TO_ONE
  • 支持生命周期回调事件 Events::prePersist / Events::preUpdate
  • 您的 ORM 对象可以与 session 解除关联,以避免 ORM 触发的插入/更新操作。**我选择给您灵活性,请使用 $detach 参数
  • 更改将分块发送到数据库

如果世界很美好,并且 Doctrine 能够为 MySQL 执行其他操作,例如执行单个插入/更新查询,则我不需要这样做。

用更少的查询浪费能源来拯救地球 :)

示例

默认用法

<?php
declare(strict_types = 1);

use Doctrine\ORM\EntityManagerInterface;
use DoctrineBulk\Bulk\BulkUpsert;

/**
 * Class DbWrite
 */
class DbWrite {
    private EntityManagerInterface $manager;

    /**
     * Creates two users in one query.
     *
     * @return int
     */
    public function updateExistingUsersAndCreateTwoUsers(): int
    {
        $dbUsers = []; // imagine some loaded users from DB and some changed data from your code 

        $bulkUpsert = new BulkUpsert($this->manager, User::class);

        foreach ($dbUsers as $dbUser) {
            $bulkUpsert->addEntity($dbUser, detach: true);
        }

        // now 2 new users
        $bulkUpsert->addEntity(new User('user 1', 'password'), detach: true);
        $bulkUpsert->addEntity(new User('user 2', 'password'), detach: true);

        $firstInsertedId = (int) $bulkUpsert->execute(maxRows: 1000);

        return $firstInsertedId;
    }
}

https://github.com/6dreams/doctrine-bulk 分支而来