简体   繁体   English

我们可以将 Laravel 枚举列设置为唯一吗

[英]Can we set laravel enum column to be unique

Can enum column be unique?枚举列可以是唯一的吗?

I have 5 different currencies in my table and only one of them has to be default, can i set unique for that column?我的表中有 5 种不同的货币,其中只有一种必须是默认货币,我可以为该列设置唯一吗?

$table->enum('default_currency', ['yes', 'no'])->unique();

No, you can't do using UNIQUE INDEX .不,您不能使用UNIQUE INDEX It will work for two rows, but in the third row it will fail, since the valid values are just two.它适用于两行,但在第三行它会失败,因为有效值只有两个。

You need to manually do this logic, and you can do it in many places.这个逻辑需要手动做,很多地方都可以做。 I personally like to do this kind of logic in a model observer , so you can watch the saving event.我个人喜欢在模型观察者中做这种逻辑,这样你就可以观看saving事件。 The logic is this:逻辑是这样的:

  1. Something try to save the currency (create or update)尝试保存货币(创建或更新)
  2. The model observer will catch the saving event模型观察者将捕获保存事件
  3. If the default_currency is set to true, you do some query like this: Currency::whereDefaultCurrency(true)->update(["default_currency"=>false])如果default_currency设置为 true,则执行如下查询: Currency::whereDefaultCurrency(true)->update(["default_currency"=>false])

Thia way, you will always have one single currency with default_currency set to true .这样,您将始终拥有一种单一货币,并且default_currency设置为true

Example of CurrencyObserver : CurrencyObserver示例:

class CurrencyObserver {
    public function saving(Currency $currency) {
        if ($currency->isDirty('default_currency') && $currency->default_currency) {
            Currency::where('default_currency', true)->update(['default_currency' => false]);
        }

        return true;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM