模式构建器 laravel 迁移在两列上是唯一的 [英] schema builder laravel migrations unique on two columns

查看:19
本文介绍了模式构建器 laravel 迁移在两列上是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在两列上设置唯一约束?

How can I set a unique constraints on two columns?

class MyModel extends Migration {
  public function up()
  {
    Schema::create('storage_trackers', function(Blueprint $table) {
      $table->increments('id');
      $table->string('mytext');
      $table->unsignedInteger('user_id');
      $table->engine = 'InnoDB';
      $table->unique('mytext', 'user_id');
    });
  }
}

MyMode::create(array('mytext' => 'test', 'user_id' => 1);
// this fails??
MyMode::create(array('mytext' => 'test', 'user_id' => 2);

推荐答案

第二个参数是手动设置唯一索引的名称.使用数组作为第一个参数来创建跨多列的唯一键.

The second param is to manually set the name of the unique index. Use an array as the first param to create a unique key across multiple columns.

$table->unique(array('mytext', 'user_id'));

或者(更整洁一点)

$table->unique(['mytext', 'user_id']);

这篇关于模式构建器 laravel 迁移在两列上是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆