entgoフィールド名の競合

Facebookのオープンソースormフレームワークent。を使用する場合は、フィールド名をLabelとして定義しないでくださいそうしないと、インスタンスがデータベースに移行されたときに次の例外が発生します。

ent/product/where.go:102:6: Label redeclared in this block

たとえば、製品テーブルを定義します。
{project} /ent/schema/product.go:

package schema

import (
	"github.com/facebook/ent"
	"github.com/facebook/ent/schema/field"
)

// Product holds the schema definition for the Product entity.
type Product struct {
    
    
	ent.Schema
}

// Fields of the Product.
func (Product) Fields() []ent.Field {
    
    
	return []ent.Field{
    
    
		field.String("name"),  // 产品名称
		field.String("label"),  // 产品标签
	}
}

// Edges of the Product.
func (Product) Edges() []ent.Edge {
    
    
	return nil
}

go generate ./entコマンドを実行して対応するormコードを生成すると、entパスの下にproductという名前のパッケージが生成されます。パッケージには、エンティティ名にちなんで名付けられたファイルproduct.goと、エンティティフィールドフィルタリングツールwhere.goが含まれています
。基本エンティティは次のとおりです。 product.goフィールドで定義:

// Code generated by entc, DO NOT EDIT.

package product

const (
	// Label holds the string label denoting the product type in the database.
	Label = "product"
	// FieldID holds the string denoting the id field in the database.
	FieldID = "id"
	// FieldName holds the string denoting the name field in the database.
	FieldName = "name"
	// FieldLabel holds the string denoting the label field in the database.
	FieldLabel = "label"

	// Table holds the table name of the product in the database.
	Table = "products"
)

// Columns holds all SQL columns for product fields.
var Columns = []string{
    
    
	FieldID,
	FieldName,
	FieldLabel,
}

// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
    
    
	for i := range Columns {
    
    
		if column == Columns[i] {
    
    
			return true
		}
	}
	return false
}

Labelという名前の定数が内部で定義されていることがわかります。
where.goでは、関連するフィルタリングメソッドがエンティティのLabelフィールドに定義されています。

// Code generated by entc, DO NOT EDIT.

package product

import (
	"goorm/ent/predicate"

	"github.com/facebook/ent/dialect/sql"
)

...

// Label applies equality check predicate on the "label" field. It's identical to LabelEQ.
func Label(v string) predicate.Product {
    
    
	return predicate.Product(func(s *sql.Selector) {
    
    
		s.Where(sql.EQ(s.C(FieldLabel), v))
	})
}

...

// LabelEQ applies the EQ predicate on the "label" field.
func LabelEQ(v string) predicate.Product {
    
    
	return predicate.Product(func(s *sql.Selector) {
    
    
		s.Where(sql.EQ(s.C(FieldLabel), v))
	})
}
...

Where.goは最初にLabel、値が等しいかどうかを比較するために、ラベルフィールドで大文字の最初の文字を使用して同じ名前のメソッドを定義します。
これにより、製品パッケージに2つのラベルが作成されます。したがって、データベースの移行を実行すると、次の例外が発生します。

ent/product/where.go:102:6: Label redeclared in this block
        previous declaration at ent/product/product.go:7:10

この場合、ラベルフィールドをproduct_labelなどの別の名前に置き換えるだけです。

おすすめ

転載: blog.csdn.net/JosephThatwho/article/details/109066460