【问题标题】:Solution for softdeletes in combination with unique constraints?结合独特约束的软删除解决方案?
【发布时间】:2020-02-05 13:30:31
【问题描述】:

我有一个表 Orders,其中包含 external_idshop_iddeleted_at 列。为了确保 external_idshop_id 的组合是唯一的,我对这 3 列有唯一的约束。

这是因为我们不计算软删除的唯一性值,因此如果在 Laravel 中 deleted_at 等于 NULL 它不是软删除,但在任何其他情况下都是软删除,这使得多个软删除记录成为可能。示例:

external_id        |shop_id   |deleted_at         |
-------------------|----------|-------------------|
1                  |         5|             [NULL]| <-- should be unique
1                  |         5|2019-12-19 13:45:22|
1                  |         5|2019-12-19 13:35:45|

这听起来不错,除了 1 个警告:MySQL 不强制 NULL 值的唯一性,这对于它的工作很重要。通常the workaround 是将可为空的默认值更改为空字符串。但是 deleted_at 是一个时间戳。

【问题讨论】:

    标签: mysql laravel soft-delete


    【解决方案1】:
    create table orders (external_id int, shop_id int, deleted_at timestamp);
    
    ALTER TABLE orders 
    ADD COLUMN `n_deleted_at` timestamp AS (COALESCE(deleted_at, '1980-01-01')) VIRTUAL;
    
    CREATE UNIQUE INDEX idx ON orders (external_id, shop_id, n_deleted_at);
    
    INSERT INTO orders (external_id, shop_id, deleted_at) VALUES (1, 5, NULL);
    INSERT INTO orders (external_id, shop_id, deleted_at) VALUES (1, 5, '2019-12-19 13:45:2');
    INSERT INTO orders (external_id, shop_id, deleted_at) VALUES (1, 5, '2019-12-19 13:35:45');
    
    INSERT INTO orders (external_id, shop_id, deleted_at) VALUES (1, 5, '2019-12-19 13:35:45');
    
    键“orders.idx”的重复条目“1-5-2019-12-19 13:35:45”
    INSERT INTO orders (external_id, shop_id, deleted_at) VALUES (1, 5, NULL);
    
    键“orders.idx”的重复条目“1-5-1980-01-01 00:00:00”

    db小提琴here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-14
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-26
      相关资源
      最近更新 更多