Gorm: DDD with GORM

Created on 21 Feb 2019  路  5Comments  路  Source: go-gorm/gorm

What version of Go are you using (go version)?

go version go1.11.5 darwin/amd64

Which database and its version are you using?

mysql 5.7

I want to use GORM for DDD but I do not know how to deal with the following problem.

I have an entity that is a User and within this, a value object that is the ID.

type User struct {
    UserId *UserId
    Name   string
}

type UserId struct {
    ID string
}

The thing is, I really want me to treat a table that would be users and the id is a text string and not a user_id table (Feel like Doctrine in PHP)

Most helpful comment

@devonblzx try

type Product struct {
    Id int
    Name   string
        Price   *Money `gorm:"embedded"`
}

All 5 comments

I've also been looking at ways of using value objects in models. Although, I think the question here may be a bit unclear. As far as I see, the OP is asking how to map a value object without it being treated as a relationship. This problem is not limited to single fields, but also value objects like the classic Money Pattern:

type Product struct {
    Id int
    Name   string
        Price   *Money
}

type Money struct {
    Amount float64
        Currency string
}

Where the product table actually has two fields: price_amount and price_currency that need to be mapped to a Money struct.

@devonblzx try

type Product struct {
    Id int
    Name   string
        Price   *Money `gorm:"embedded"`
}

@inliquid Thanks. Looks like what I'm after. Just wasn't searching for the right verbiage.

While they aren't well-documented, for anyone else that comes across these, EMBEDDED and EMBEDDED_PREFIX are listed here: http://gorm.io/docs/models.html#Supported-Struct-tags

Another option is embed struct by not providing field name, in the example above leave just *Money.

ty @inliquid and @devonblzx

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bramp picture bramp  路  3Comments

fieryorc picture fieryorc  路  3Comments

alanyuen picture alanyuen  路  3Comments

superwf picture superwf  路  3Comments

Ganitzsh picture Ganitzsh  路  3Comments