Laravel 4: making a combination of values/columns unique

后端 未结 5 1938
灰色年华
灰色年华 2020-12-14 01:07

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

相关标签:
5条回答
  • 2020-12-14 01:24

    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

    0 讨论(0)
  • 2020-12-14 01:30

    You can try this

    $table->string("name");
    $table->string("email")->unique("name")
    
    0 讨论(0)
  • 2020-12-14 01:34

    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.

    0 讨论(0)
  • 2020-12-14 01:35

    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

    0 讨论(0)
  • 2020-12-14 01:42

    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'.

    0 讨论(0)
提交回复
热议问题