通过Laravel迁移添加XOR约束

时间:2018-04-16 07:18:53

标签: php laravel

我正在尝试使用Laravel的迁移功能构建一个包含此结构的表:

------------------------------------
| Data  | Rules | Allow | Restrict |
------------------------------------
| item1 | rule1 | 1,3   |   null   |
| item2 | rule2 | null  |  2,5,6   |
------------------------------------

对于每个条目,Allow或Restrict必须具有非null值,但不能同时具有两者。我发现this comment听起来像我需要的条件,但我需要用Laravel可以理解的格式来表达它。

1 个答案:

答案 0 :(得分:1)

我认为有两个很好的解决方案

  1. 分隔2个表格中的数据
  2. 表1 - >数据,规则,约束(FK)

    Table2-> id(PK,由Table1引用),content(允许/限制数字),isAllow(bool)

    这样就可以在数据库中执行约束。这是更好的解决方案,因为现在您的数据库中没有null个值。规范化是一件好事。

    1. 在插入
    2. 之前使用事件侦听器进行检查

      https://laravel.com/docs/5.6/eloquent#events

      public function creating(Table1 $t1)
      {
             // check if 1 is null and 1 is not null before creating
      }