go-ozzo / ozzo-dbx

A Go (golang) package that enhances the standard database/sql package by providing powerful data retrieval methods as well as DB-agnostic query building capabilities.
MIT License
636 stars 91 forks source link

Why Id populates from joined table? #27

Closed kolkov closed 7 years ago

kolkov commented 7 years ago

Hi, Qiang! Happy New Year 2017! I use this code to populate FeedPersonName struct from MySQL tables. But Feed.Id, Feed.CreatedAt etc. populates with Id, CreatedAt etc. from Person table not from Feed. Is it correct?

Feed

type Feed struct{
    Id int
    deleted bool
    PersonId int
    Heading string
    Body string
    CreatedAt time.Time
    UpdatedAt time.Time
}

type FeedPersonName struct {
    Feed
    Person PersonName
}

func (m FeedPersonName) TableName() string {
    return "feed"
}

PersonName

type PersonName struct {
    LastName string `json:"last_name"`
    FirstName string `json:"first_name"`
}

func (m PersonName) TableName() string {
    return "person"
}

FeedDAO

func (dao *FeedDAO) Query(rs app.RequestScope, offset, limit int) ([]models.Feed, error) {
    feed := []models.Feed{}
    err := rs.Tx().Select().InnerJoin("person", dbx.NewExp("`feed`.`person_id` = `person`.`id`")).OrderBy("id").Offset(int64(offset)).OrderBy("feed.id DESC").Limit(int64(limit)).All(&feed)
    return feed, err
}

image

image

image

qiangxue commented 7 years ago

There are two Id columns being returned. This is a bit special. The current implementation will take the second Id column. I suggest you avoid this situation by explicitly selecting one Id column that you really want.

kolkov commented 7 years ago

Yes, I did the same, but it seems to me that this is not quite right ... Thanks!

qiangxue commented 7 years ago

What is not quite right?