Why GORM including polymorphic relation automatically

39 Views Asked by At

Using GORM. I've setup a polymorphic relation with User -> Media. Other models also use Media to store their images. Following is the User model

type User struct {
    ID uint `json:"id" gorm:"primaryKey"`

    Name     string `json:"name" gorm:"type:varchar(30); not null;"`
    Email    string `json:"email" gorm:"type:varchar(40); not null;uniqueIndex;"`
    // ...

    // relations
    Image  Media   `json:"image" gorm:"polymorphic:Owner;constraint:OnDelete:CASCADE;"`
    Groups []Group `json:"groups" gorm:"many2many:group_user;"`
    // ...

    CreatedAt time.Time `json:"created_at" gorm:"type:datetime"`
    UpdatedAt time.Time `json:"updated_at" gorm:"type:datetime"`
}

Querying the User like this

var user model.User
res := database.DB.First(&user, id) // id is authenticated users id (uint)

After seeing the result i'm surprised that this included image (Media) automatically when other relations is not included.

{
    "id": 11,
    "name": "the user name",
    "email": "[email protected]",
    // ...

    "image": { // here it is, this is zero value struct as the relation doesn't have any record
      "id": 0,
      "name": "",
      //...
      "owner_id": 0,
      "owner_type": ""
    },
    "created_at": "2024-03-07T22:00:04+06:00",
    "updated_at": "2024-03-09T17:01:11+06:00"
  }

What may causing it?

0

There are 0 best solutions below