sqlboiler
sqlboiler copied to clipboard
Feature: Allow to delete all related items, when related arg is omitted.
Sometimes a record needs to be deleted which is referenced by other relations. So, those relations need to be deleted first.
At the moment this template code:
https://github.com/volatiletech/sqlboiler/blob/e004393fa62ca053ec76d14df63d2e066cd2de23/templates/12_relationship_to_many_setops.go.tpl#L317-L323
Renders to:
func (o *BasePrice) RemoveArticles(ctx context.Context, exec boil.ContextExecutor, related ...*Article) error {
var err error
query := fmt.Sprintf(
"delete from \"shop\".\"article_base_prices\" where \"base_price_id\" = $1 and \"article_id\" in (%s)",
strmangle.Placeholders(dialect.UseIndexPlaceholders, len(related), 2, 1),
)
related seems to be optional from the method's signature. However, when omitted the query fails because the article_id in set ends up empty. So in order to remove all relations from the join table, I would first need to obtain all of them from the database, which could be avoided.
My proposal would be to only include the and "relation" in (%s) if related is provided. Something like:
query := "delete from \"shop\".\"article_base_prices\" where \"base_price_id\" = $1"
if len(related) > 0 {
query += fmt.Sprintf(
" and \"article_id\" in (%s)",
strmangle.Placeholders(dialect.UseIndexPlaceholders, len(related), 2, 1),
)
}
Note: Probably not the best way to build a string
As a workaround, I'm currently using raw queries to remove the relations in join tables.
I think if you want to delete all related items from a relationship you can use: yourModel.ArticleBasePrices().DeleteAll() which doesn't require fetching records.