Skip to content

Cascade deleting associated to-many records when it's empty #388

@skolodyazhnyy

Description

@skolodyazhnyy

I'm having troubles figuring out how to cascade save an empty slice of associated records.

Let's say I have:

type ShoppingCart struct {
	ID                    string             `db:"id,primary"`
	Items                 []ShoppingCartItem `ref:"id" fk:"cart_id" autoload:"true" autosave:"true"`
}

type ShoppingCartItem struct {
	ID        string    `db:"id,primary"`
	ProductID string    `db:"product_id"`
	Quantity  int32     `db:"quantity"`
}

When saving shopping cart, items are automatically cascaded, unless there are no items. If I want to empty shopping cart I want to save it like so:

// user adds item to the shopping cart
cart.Items = []ShoppingCartItem{item1}
rel.Update(ctx, cart) // item1 inserted ✅ 

// user empties cart
cart.Items = nil // or []ShoppingCartItem{}
rel.Update(ctx, cart) // item1 is not deleted ⚠️ 

The issue here is that Update thinks items haven't been loaded, so it does not delete existing items.

Is there way to force make rel to delete item1?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions