PHPackages                             tourze/doctrine-upsert-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. tourze/doctrine-upsert-bundle

ActiveLibrary[Database &amp; ORM](/categories/database)

tourze/doctrine-upsert-bundle
=============================

Doctrine的upsert支持

1.0.0(6mo ago)02.5k5MITPHPCI passing

Since Apr 7Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/doctrine-upsert-bundle)[ Packagist](https://packagist.org/packages/tourze/doctrine-upsert-bundle)[ RSS](/packages/tourze-doctrine-upsert-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (24)Versions (6)Used By (5)

doctrine-upsert-bundle
======================

[](#doctrine-upsert-bundle)

[English](README.md) | [中文](README.zh-CN.md)

[![Latest Version](https://camo.githubusercontent.com/5918e6da5c41a59605f856edfc866e5e37e60d794290b44069bb62983ed8ad91/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f746f75727a652f646f637472696e652d7570736572742d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/doctrine-upsert-bundle)[![License: MIT](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](./LICENSE)[![PHP Version](https://camo.githubusercontent.com/9c349678ae3bbef594a69893f229dd63beee465386cdab2c4362ab4fa5e4401e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f746f75727a652f646f637472696e652d7570736572742d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/doctrine-upsert-bundle)[![Total Downloads](https://camo.githubusercontent.com/bb1f6549f21f02c06c61ee053f12a414413fb3852519bd12b753c98a9ab9dc18/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f746f75727a652f646f637472696e652d7570736572742d62756e646c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tourze/doctrine-upsert-bundle)[![Build Status](https://github.com/tourze/doctrine-upsert-bundle/workflows/CI/badge.svg)](https://github.com/tourze/doctrine-upsert-bundle/actions)[![Code Coverage](https://camo.githubusercontent.com/f1bdabf77d458441c465b46b17e94a1b880b861212c22e27d434be4bbb20eb86/68747470733a2f2f636f6465636f762e696f2f67682f746f75727a652f646f637472696e652d7570736572742d62756e646c652f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/tourze/doctrine-upsert-bundle)

Efficient UPSERT (insert or update) capabilities for Doctrine ORM with automatic SQL generation and multi-database support.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Quick Start](#quick-start)
    - [Configuration](#configuration)
    - [Basic Usage](#basic-usage)
    - [Batch UPSERT](#batch-upsert)
    - [Low-Level UPSERT](#low-level-upsert)
- [Entity Requirements](#entity-requirements)
- [Advanced Usage](#advanced-usage)
    - [Custom Update Time Handling](#custom-update-time-handling)
    - [Extending with Custom Providers](#extending-with-custom-providers)
- [API Reference](#api-reference)
    - [UpsertManager](#upsertmanager)
    - [Supported Platforms](#supported-platforms)
- [Contributing](#contributing)
- [License](#license)
- [Changelog](#changelog)

Features
--------

[](#features)

- **Single and Batch UPSERT Operations**
    - MySQL: `INSERT ... ON DUPLICATE KEY UPDATE`
    - SQLite: `INSERT ... ON CONFLICT ... DO UPDATE SET`
- **Automatic Database Platform Detection** - Works seamlessly with MySQL and SQLite
- **Smart Unique Constraint Detection** - Automatically identifies unique constraints from entity metadata
- **Extensible Provider System** - Custom UPSERT providers via `ProviderInterface`
- **Safe Error Handling** - Prevents EntityManager closure on errors
- **Automatic Timestamp Management** - Handles `create_time` and `update_time` fields intelligently

Requirements
------------

[](#requirements)

- PHP &gt;= 8.1
- doctrine/orm &gt;= 3.0
- doctrine/dbal &gt;= 4.0
- symfony &gt;= 6.4

Installation
------------

[](#installation)

```
composer require tourze/doctrine-upsert-bundle
```

Quick Start
-----------

[](#quick-start)

### Configuration

[](#configuration)

Register the bundle in `config/bundles.php`:

```
return [
    Tourze\DoctrineUpsertBundle\DoctrineUpsertBundle::class => ['all' => true],
];
```

### Basic Usage

[](#basic-usage)

```
use App\Entity\User;
use Tourze\DoctrineUpsertBundle\Service\UpsertManager;

// Inject UpsertManager (or use dependency injection)
public function __construct(
    private UpsertManager $upsertManager
) {}

// Single entity upsert
$user = new User();
$user->setEmail('user@example.com');
$user->setName('John Doe');

// Returns the persisted entity (may be different from input)
$persistedUser = $this->upsertManager->upsert($user);
```

### Batch UPSERT

[](#batch-upsert)

```
// Batch upsert with array data
$userData = [
    ['email' => 'user1@example.com', 'name' => 'User 1'],
    ['email' => 'user2@example.com', 'name' => 'User 2'],
];

$affectedRows = $this->upsertManager->executeBatch($userData, User::class);
```

### Low-Level UPSERT

[](#low-level-upsert)

```
// Direct SQL execution
$insertData = ['email' => 'user@example.com', 'name' => 'John'];
$updateData = ['name' => 'John Doe Updated']; // Optional

$affectedRows = $this->upsertManager->execute('users', $insertData, $updateData);
```

Entity Requirements
-------------------

[](#entity-requirements)

Your entities must have unique constraints defined for UPSERT operations:

```
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'users')]
#[ORM\UniqueConstraint(name: 'user_email_unique', columns: ['email'])]
class User
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\Column(type: 'string', unique: true)]
    private string $email;

    #[ORM\Column(type: 'string')]
    private string $name;

    // Or use individual unique columns
    // #[ORM\Column(type: 'string', unique: true)]
    // private string $username;
}
```

Advanced Usage
--------------

[](#advanced-usage)

### Custom Update Time Handling

[](#custom-update-time-handling)

The bundle automatically handles `update_time` fields:

```
class User
{
    #[ORM\Column(type: 'datetime')]
    private \DateTime $createTime;

    #[ORM\Column(type: 'datetime')]
    private \DateTime $updateTime;

    public function setUpdateTime(\DateTime $updateTime): self
    {
        $this->updateTime = $updateTime;
        return $this;
    }
}
```

### Extending with Custom Providers

[](#extending-with-custom-providers)

Create custom database platform support:

```
use Tourze\DoctrineUpsertBundle\Service\ProviderInterface;

class PostgreSQLUpsertProvider implements ProviderInterface
{
    public function supports(string $platform): bool
    {
        return $platform === 'postgresql';
    }

    public function getUpsertQuery(string $table, array $insertData, array $updateData): string
    {
        // Implementation for PostgreSQL UPSERT
        return "INSERT INTO {$table} ... ON CONFLICT ... DO UPDATE SET ...";
    }
}
```

API Reference
-------------

[](#api-reference)

### UpsertManager

[](#upsertmanager)

- `upsert(object $entity, bool $fetchAgain = true): object` - Upsert single entity
- `execute(string $table, array $insertData, array $updateData = []): int` - Execute raw upsert
- `executeBatch(array $data, string $repositoryClass): int` - Batch upsert operation

### Supported Platforms

[](#supported-platforms)

- **MySQL**: Uses `INSERT ... ON DUPLICATE KEY UPDATE`
- **SQLite**: Uses `INSERT ... ON CONFLICT ... DO UPDATE SET`

Contributing
------------

[](#contributing)

1. Fork the repository
2. Create a feature branch
3. Follow PSR-12 coding standards
4. Add tests for new features
5. Submit a pull request

License
-------

[](#license)

MIT License © tourze

Changelog
---------

[](#changelog)

See \[CHANGELOG.md\] or Git history for version updates and changes.

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance71

Regular maintenance activity

Popularity16

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity41

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~51 days

Total

5

Last Release

192d ago

Major Versions

0.1.1 → 1.0.02025-10-31

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-doctrine-upsert-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-doctrine-upsert-bundle/health.svg)](https://phpackages.com/packages/tourze-doctrine-upsert-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

7310.3k29](/packages/open-dxp-opendxp)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
