简体   繁体   中英

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?

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

No, you can't do using 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. 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])

Thia way, you will always have one single currency with default_currency set to true .

Example of 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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