gorm icon indicating copy to clipboard operation
gorm copied to clipboard

Add ability to add associations to update on save instead of only omitting them

Open Brian-McM opened this issue 3 years ago • 2 comments

Describe the feature

Please excuse me if this has been discussed before...

Currently it seems like you can only omit Associations from getting saved. You can omit saving all associations (Omit(clause.Associations)), or you can omit saving specific ones (Omit("AssociationName")).

I would like the ability to add specific associations, and unless an association is specified it is not saved.

I think a simple way of doing this would be to evaluate the Select options after the Omit options here. This would allow you to omit all associations then add back the specific ones you want.

Motivation

Let's say I have model Object and this model has associations Association1, Association2, and Association3, and when I save Object I only want Association2 to be saved. To do this the query would look as follows:

gormDBCli.Omit("Association1", "Association3").Save(objects)

The issue I have with this method is that if somebody comes and adds a new association to Object they then need to remember to omit that association from every Save (or create or update).

Related Issues

Brian-McM avatar Jul 29 '22 18:07 Brian-McM

I think a simple way of doing this would be to evaluate the Select options after the Omit options here. This would allow you to omit all associations then add back the specific ones you want.

This is a breaking change, in the chained api we have no way of knowing the actual purpose of user Select and Omit. We specify an order, there is no right or wrong, it just happens to check the Select first.

tx.Select("Association1", "Association2")
tx.Omit("Association3")
tx.Omit("Association2")
tx.Select("Association2")
tx.Save(...) // we don't know their purpose

The issue I have with this method is that if somebody comes and adds a new association to Object they then need to remember to omit that association from every Save (or create or update).

I think Session or Scope can be used here to distinguish them https://gorm.io/docs/session.html#content-inner https://gorm.io/docs/scopes.html#content-inner

a631807682 avatar Jul 31 '22 05:07 a631807682

I think Session or Scope can be used here to distinguish them

Can you explain this a little more, or give an example of what you mean, i.e. how exactly can I use Session or Scope to not update any association in my project on save by default.

Brian-McM avatar Aug 08 '22 20:08 Brian-McM

This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days

github-actions[bot] avatar Aug 04 '23 02:08 github-actions[bot]

Not stale

mnussbaum avatar Aug 04 '23 07:08 mnussbaum