Your Question
I have two model structs. When I combine these two structs for querying, a problem occurs.
The document you expected this should be explained
type User struct {
ID uuid.UUID `gorm:"primarykey;column:id"`
Name string `gorm:"column:name"`
}
func (User) TableName() string {
return "users"
}
type Order struct {
ID uuid.UUID `gorm:"primarykey;column:id"`
UserID uuid.UUID `gorm:"column:user_id"`
Name string `gorm:"column:name"`
}
func (Order) TableName() string {
return "orders"
}
It is correct when I use the following query. When the order is not matched, nil is returned. Like this user: {31e8f5fe-9848-4088-b786-ff75f1ab7563 user 1} order: <nil>
user, order := &User{}, &Order{}
userTable, orderTable := user.TableName(), order.TableName()
var uo []struct {
User
*Order
}
err = db.Model(user).Select(
userTable+".*, "+orderTable+".*",
).Joins(
"LEFT JOIN "+orderTable+" ON "+userTable+".id = "+orderTable+".user_id",
).Where(userTable+".id = ?", "31e8f5fe-9848-4088-b786-ff75f1ab7563").Scan(&uo)
But when I use the following order struct. When the order is not matched, nil is not returned. Like this user: {31e8f5fe-9848-4088-b786-ff75f1ab7563 user 1} order: &{00000000-0000-0000-0000-000000000000 00000000-0000-0000-0000-000000000000 <nil>}
type Order struct {
ID uuid.UUID `gorm:"primarykey;column:id"`
UserID uuid.UUID `gorm:"column:user_id"`
Name *string `gorm:"column:name"`
}
But uuid.UUID will still return nil. If it is string or *int etc., it will not return nil.
Expected answer
I want to know why this is happening. It makes my logic for judging whether the order matches inconsistent.