[英]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:逻辑是这样的:
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.