Gorm: Has Many Getting Empty (null) Result

Created on 21 Nov 2015  路  2Comments  路  Source: go-gorm/gorm

I am trying to define one to many relation . I have read all the docs over and over again . Could not find a way to do it .

func GetUser1(c *gin.Context) {
    var user models.User
    var activities models.UserActivity
    query := DB.Debug().Find(&user, 1).Model(&user).Related(&activities).Error
    if query != nil {
        panic(query)
    }
    c.JSON(200, &user)
}

My Models are ..

type User struct {
    Id       int64
    Username string
    Password string `json:"-"`
    Email    string `json:",omitempty"`
    UserActivities []UserActivity
}
type UserActivity struct {
    Id         int64
    UserId     int64 `json:"-"`
    ActorId    int64
    CreatedAt  time.Time
}

Debug Results are

[2015-11-21 22:21:54]  [3.17ms]  SELECT  * FROM `users`  WHERE (`id` = '1')
[2015-11-21 22:21:54]  [1.39ms]  SELECT  * FROM `user_activities`  WHERE (`user_id` = '1')

But I am getting null results

{
    "Id": 1,
    "Username": "test1",
    "Email": "[email protected]",
    "UserActivities": null
}

All the primary keys and Indexes are right . However if i replace UserActivities []UserActivity with UserActivities []UserActivity then i get only one row which seems to be right but why UserActivities []UserActivity giving no results

question

Most helpful comment

db.Preload("UserActivities").Find(&user, 1)

All 2 comments

db.Preload("UserActivities").Find(&user, 1)

I'm still confused, what the function of .Related() ?
When I should use Preload() or Related() ?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

sredxny picture sredxny  路  3Comments

youtwo123 picture youtwo123  路  3Comments

izouxv picture izouxv  路  3Comments

leebrooks0 picture leebrooks0  路  3Comments

easonlin404 picture easonlin404  路  3Comments