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

When using embedded structure query, the result is not consistent with the expectation #7317

Open
Axb12 opened this issue Dec 13, 2024 · 0 comments
Assignees
Labels
type:question general questions

Comments

@Axb12
Copy link

Axb12 commented Dec 13, 2024

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.

@Axb12 Axb12 added the type:question general questions label Dec 13, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:question general questions
Projects
None yet
Development

No branches or pull requests

2 participants