Laravel 4: making a combination of values/columns unique

与世无争的帅哥 提交于 2019-12-17 23:06:35

问题


I'm importing a bunch of csv entries in my database with Laravel 4.

I can't really point at one column that has to be unique, it's a combination of 5 columns that makes it unique. However: how does one define this in Laravel?

Option 1: schema builder
You can use the $table->unique('email') method, but that only seems to allow one column, not a combination of columns.

Option 2: Validation
Less preferable, but I could validate the model before inserting it. However, again, using 'unique:[table]' validation rules, it will return an error when just one of the column values isn't unique, not a combination of them.

Can anyone tell me how I should go about this?
I'm sure I'm missing something, but I could use a push in the right direction :-)

Thanks,

Dieter


回答1:


You can combine:

$table->unique( array('email','name') );

And pretty much everything in Laravel will accept arrays to do whatever you need to with 'more than one'.




回答2:


Use Schema Builder's unique() method to define your data model, as Antonio mentioned.

Additionally, if you want to use validation on your model, consider my custom Validator rule for multiple UNIQUE indexes: https://github.com/felixkiss/uniquewith-validator




回答3:


You can also do this;

$table->unique(["column1", "column2"], 'uq_columns');

Which means that you will have a unique column combination of all the columns i.e. column1 and column2




回答4:


I know this question is for Laravel 4, but I just came across this on searches and found a solution for Laravel >= 5.3

Here it is:

Of course, the migration may look something like

$table->unique( array('email','name') );

Then to validate this, you do not need to use custom rules, just advanced rules:

'email' => Rule::unique('users')->where(function ($query) use ($request) {
    return $query->where('name', $request->name);
}),

Of course, you may want to validate name before of this. The name should be required so that you may finish with something like this:

'name' => 'required|max:255',
'email' => Rule::unique('users')->where(function ($query) use ($request) {
    return $query->where('name', $request->name);
}),

I hope it helps.




回答5:


You can try this

$table->string("name");
$table->string("email")->unique("name")


来源:https://stackoverflow.com/questions/16990723/laravel-4-making-a-combination-of-values-columns-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!