如何删除一列?

huangapple go评论85阅读模式
英文:

Ent. how to remove a column?

问题

我在我的Go项目中已经有一个Ent模型。但是我需要从模型中删除一些列。当我更新我的模型时,它不起作用。运行迁移会导致运行时错误。如何在Ent ORM中删除现有模型的列?

英文:

I have already an Ent model in my go project. But I need to remove some columns from the model.
It not works when I update my model. Running migration results runtime error.
How can I remove a column from existing model in Ent. ORM?

答案1

得分: 1

您可以通过在迁移中设置WithDropIndexWithDropColumn选项来简单地更改模型以删除某些字段,如下所示:

package main

import (
    "context"
    "log"
    
    "<project>/ent"
    "<project>/ent/migrate"
)

func main() {
    client, err := ent.Open("mysql", "root:pass@tcp(localhost:3306)/test")
    if err != nil {
        log.Fatalf("failed connecting to mysql: %v", err)
    }
    defer client.Close()
    ctx := context.Background()
    // 运行迁移。
    err = client.Schema.Create(
        ctx, 
        migrate.WithDropIndex(true),
        migrate.WithDropColumn(true), 
    )
    if err != nil {
        log.Fatalf("failed creating schema resources: %v", err)
    }
}

更多信息请参见文档

英文:

You can change model simply to remove some fields and this will works if you set WithDropIndex and WithDropColumn options within migration as follow:

package main

import (
    &quot;context&quot;
    &quot;log&quot;
    
    &quot;&lt;project&gt;/ent&quot;
    &quot;&lt;project&gt;/ent/migrate&quot;
)

func main() {
    client, err := ent.Open(&quot;mysql&quot;, &quot;root:pass@tcp(localhost:3306)/test&quot;)
    if err != nil {
        log.Fatalf(&quot;failed connecting to mysql: %v&quot;, err)
    }
    defer client.Close()
    ctx := context.Background()
    // Run migration.
    err = client.Schema.Create(
        ctx, 
        migrate.WithDropIndex(true),
        migrate.WithDropColumn(true), 
    )
    if err != nil {
        log.Fatalf(&quot;failed creating schema resources: %v&quot;, err)
    }
}

For more information see documentation

huangapple
  • 本文由 发表于 2022年3月14日 15:16:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/71464160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定