Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ambiguous column reference when join #1472

Closed
tungnk1993 opened this issue Dec 9, 2019 · 2 comments
Closed

Ambiguous column reference when join #1472

tungnk1993 opened this issue Dec 9, 2019 · 2 comments

Comments

@tungnk1993
Copy link

Structs

type Client struct {
   Id int64
   Name string
}

type Trade struct {
   Id int64
   ClientId int64
   Client *Client
}

Query
db.Model(&Trade).Where("id = ", tradeId).Relation("Client").Select()

Error encountered: Column Id ambiguous. Not sure what's the proper way to work around this
Would be great if someone can help

@nesymno
Copy link

nesymno commented Jan 29, 2020

Did you fix it? If yes, how? :)

@sittipongwork
Copy link

today i found this error but no answer, but i can fix it.

it's can join in 2 way

  1. add alias tag in struct and use alias.column (if no tag alias:employee you can't use employee.columnName)
...
tableName struct{}  `pg:"alias:employee"`
...
  1. Relation function
type Employee struct {
	tableName struct{}  `pg:"alias:employee"`
	ID        int32     `pg:"id,type:serial,default:auto_increment,pk" json:"id"`
	Name      string    `pg:"name,notnull" json:"name"`
	Age       int       `pg:"age,notnull" json:"age"`
	CompanyID int       `pg:"fk:company_id,rel:has-one" json:"company_id"`
	Company   *Company  `pg:"rel:has-one" json:"company,omitempty"`
	CreatedAt time.Time `pg:"created_at" json:"created_at"`
	UpdatedAt time.Time `pg:"updated_at" json:"updated_at"`
	IsActive  bool      `pg:"is_active,notnull" json:"is_active"`
}

type Company struct {
	tableName struct{}   `pg:"alias:company"`
	ID        int32      `pg:"id,type:serial,default:auto_increment,pk" json:"id"`
	Employee  []Employee `pg:"rel:has-many" json:"employee_list,omitempty"`
	Title     string     `pg:"title,notnull" json:"title"`
	Address   string     `pg:"address,notnull" json:"address"`
	IsActive  bool       `pg:"is_active,notnull" json:"is_active"`
}

func GetActiveEmployeeInCompany(companyID int) (companyData Company, err error) {
	client := dbconnect.Connect()
	defer client.Close()
	c := Company{}
	if err := client.Model(&c).
		OrderExpr("products.updated_at DESC").
		Where("company.id = ?", companyID).
		Where("company.is_active IS TRUE").
		Relation("Employee", func(q *pg.Query) (*pg.Query, error) {
			return q.Where("is_active IS TRUE"), nil
		}).Select(); err != nil {
		return c, err
	}

	// ...

	return c, nil
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants