Gorm : belongs to, struct model creating problem

303 views Asked by At

A Post should belongs to a User, and has connection to the belonged User, plus both ID is uuid string.

Here's my Post struct model :

type Post struct {
    ID        string `gorm:"primarKey"`
    Title     string `gorm:"unique"`
    Body      string
    UserID    string
    User User `gorm:"foreignKey:UserID;references:ID"`
}

and my User model :

type User struct {
    ID       string `gorm:"primaryKey"`
    Email    string `gorm:"unique"`
    Name     string `gorm:"unique"`
    Password string
}

This is a function I use to create Post

func PostCreate(datas PostInputForm, user User) (Post, error) {
    post := models.Post{Title: datas.Title, Body: datas.Body, UserID: user.ID}
    dbIns := database.GetDB()
    if err := dbIns.Create(&post).Error; err != nil {
        return Post{}, err
    }

    log.Println("Post's User ID : ", post.UserID)
    log.Println("Post's User : ", post.User)

    return post, nil
}

Here's the printing output :

2022/11/26 22:25:22 Post's User ID :  715b27dc-cbb7-4511-a591-914fc5e0b75e
2022/11/26 22:25:22 Post's User :  {   }

The problem it's that the created User field of the Post model (post.User) is empty in the second printing output.

I wonder if this is how it is supposed to be ?

Like I want the Post.User to be auto loaded inside a new create Post.

From my previous experience with FastAPI & Sqlalchemy (python), shouldn't this post.User be auto assigned to a User that has same ID with the user.ID that was passed to ?

I expected the second printing output, not empty, but to be some thing like this :

2022/11/26 22:25:22 Post author is :  { user_id, user_name, user_email, user_password }

P.S. Tried pass user instead of just user.ID, but it cause an error

post := models.Post{Title: datas.Title, Body: datas.Body, User: user}
1

There are 1 answers

0
Shahriar Ahmed On

The behavior you got from gorm is normal. That means gorm doesn't explicitly do any query to extract User data from User table. It only runs a Insert query. Here is the query when you will get while running PostCreate function. Please notice the query.

INSERT INTO `posts` (`title`,`body`,`user_id`) VALUES ("ABC","Good Work!","98e86a24-1b01-4ef9-aaea-fd0181d128ea") RETURNING `id`

If you want User data you will need to use Preload or Join query.