Your Question

from the explanation in the official document for updating associated objects, we should use replace but the problem is it will not replace instead the previous object will be orphaned which is wrong.

func (d *dictionaryStore) Update(ctx context.Context, dictionary *DictionaryEntry) error {
    if err := d.Get(ctx, &DictionaryEntry{Model: gorm.Model{ID: dictionary.ID}}); err != nil {
        return err
    }

    if err := d.db.WithContext(ctx).Preload("OfflineGameDictionaryEntries").Preload("OnlineGameDictionaryEntry").Where("id = ?", dictionary.ID).Updates(dictionary).Error; err != nil {
        return err
    }

    if err := d.db.Model(&dictionary).Association("OfflineGameDictionaryEntries").Replace(&dictionary.OfflineGameDictionaryEntries); err != nil {
        return err
    }

    if err := d.db.Model(&dictionary).Association("OnlineGameDictionaryEntry").Replace(&dictionary.OnlineGameDictionaryEntry); err != nil {
        return err
    }

    return nil
}

The document you expected this should be explained

https://gorm.io/docs/associations.html

Expected answer

How we should update the associated objects correctly?

Comment From: saeidee

Replace will not delete the associated model but just replace it, here is a related issue: https://github.com/go-gorm/gorm/issues/4010.

Comment From: amirrmonfared

Replace will not delete the associated model but just replace it, here is a related issue: #4010.

Thanks for your answer, so how we can update associations properly in this case with new data?

Comment From: a631807682

use unscoped https://github.com/go-gorm/gorm/pull/6246

Comment From: amirrmonfared

@a631807682 Thanks for your help and for answering my question, it will be great to improve the documentation in general and also for this case because it's not explained there. If I can help improve the document please let me know, I would be happy to contribute!

Comment From: a631807682

@a631807682 Thanks for your help and for answering my question, it will be great to improve the documentation in general and also for this case because it's not explained there. If I can help improve the document please let me know, I would be happy to contribute!

We already have a PR for this documentation, your contributions are welcome. You can help us review and translate it. If there are more examples, welcome to create other PRs to supplement it