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

How to Update with a multi column primary key? #101

Closed OSHW-Rico closed 2 years ago

OSHW-Rico commented 2 years ago

I am trying to update with:

// update
err = repo.Update(ctx, entity.Driver{
    SessionID: 1241414,
    CarIdx:    11,
    CarNumber: "33",
    CreatedAt: time.Now(),
    UpdatedAt: time.Now(),
})

.

// Update saves the changes to an driver in the database.
func (r repository) Update(ctx context.Context, driver entity.Driver) error {
    return r.db.With(ctx).Model(&driver).Update()
}

The SessionID and CardIdx are the primary key fields.

CREATE TABLE driver
(
    session_id INTEGER NOT NULL,
    car_idx INTEGER NOT NULL,
    PRIMARY KEY (session_id, car_idx),
    ....

image

OSHW-Rico commented 2 years ago

I don't understand all your magic how the model is build, but the model of Driver does not have any Primary Keys.

// Driver represents an driver record.
type Driver struct {
    SessionID               int
    CarIdx                  int       `yaml:"CarIdx"`
    UserName                string    `yaml:"UserName"`
    AbbrevName              string    `yaml:"AbbrevName"`
    Initials                string    `yaml:"Initials"`

image

OSHW-Rico commented 2 years ago

Found the solution.

https://github.com/go-ozzo/ozzo-dbx#crud-operations

If the struct has a field named ID or Id, by default the field will be treated as the primary key field. If you want to use a different field as the primary key, tag it with db:"pk". You may tag multiple fields for composite primary keys. Note that if you also want to explicitly specify the column name for a primary key field, you should use the tag format db:"pk,col_name".