如何在 Laravel Migration 中使列唯一并为其编制索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28859969/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:04:02  来源:igfitidea点击:

How to make column unique and index it in Laravel Migration?

laravellaravel-4

提问by iori

I would like to altermy one of my columnon my table - and make them a unique index.

我想把alter我的一个column放在我的桌子上 - 并将它们制作成unique index.

I tried :

我试过 :

public function up()
    {
        Schema::table('inventories', function($table)
        {

            $table->string('sku',255)->unique();

        });
    }

I get :

我得到:

enter image description here

在此处输入图片说明

What is the most efficient way to do that ?

最有效的方法是什么?

回答by lukasgeiter

You can add indexes separately from their definition. As documented here

您可以将索引与其定义分开添加。如此处所述

Schema::table('inventories', function($table)
{
    $table->unique('sku');
});

回答by iori

I got it.

我知道了。

I did this :

我这样做了:

public function up()
    {

        DB::update('alter table `inventories` modify `sku` VARCHAR(200) UNIQUE NOT NULL');

    }

and now It works :

现在它有效:

enter image description here

在此处输入图片说明