代码之家  ›  专栏  ›  技术社区  ›  Léo Coco

mySQL-依赖于其他列的唯一性约束

  •  0
  • Léo Coco  · 技术社区  · 6 年前

    item 其列为 id type code image

    类型列

    类型 是枚举,可以是 text logo .

    type === 'text' 形象 null

    如果 type === 'logo' 然后 无效的

    如果 type=='文本' 单一性定义为 type=='徽标' 形象

    问题

    如何在mySQL中编写这个唯一的约束?和拉维一起移民?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jonathon    6 年前

    我认为你不能用这种方式声明一个唯一的约束。你可以简化你的桌子 type 列,但使用单个字段 code logo value 价值

    Schema::create('items', function (Blueprint $table) {
        // Your fields here...
    
        $table->unique(['type', 'value']);
    });
    

    image

    class Item extends Model
    {
        public function getCodeAttribute()
        {
            return $this->type === 'text' ? $this->value : null;
        }
    
        public function getImageAttribute()
        {
            return $this->type === 'logo' ? $this->value : null;
        }
    }
    

    这将允许您访问 代码 形象 价值 null Item

    $text = new Item(['type' => 'text', 'value' => 'Hello World!']);
    echo $text->code; // Hello World!
    echo $text->image; // null
    
    $logo = new Item(['type' => 'logo', 'value' => 'your-image.jpg']);
    echo $text->code; // null
    echo $text->image; // your-image.jpg
    
        2
  •  0
  •   atf.sgf    6 年前

    在迁移表中创建默认值为空的代码和图像列,然后如果不将值设置为列,则其值将自动为空

    $table->enum('type', ['image', 'code']);
    $table->string('image')->default(null);
    $table->string('code')->default(null);