deleteRefRecords checks if related records has to be deleted (if `CascadeDelete` is set) OR just unset the record id from any relation field values (if they are not required). NB! This method is expected to be called from inside of a transaction.
(app App, mainRecord *Record, refRecords []*Record, field Field)
| 1579 | // |
| 1580 | // NB! This method is expected to be called from inside of a transaction. |
| 1581 | func deleteRefRecords(app App, mainRecord *Record, refRecords []*Record, field Field) error { |
| 1582 | relField, _ := field.(*RelationField) |
| 1583 | if relField == nil { |
| 1584 | return errors.New("only RelationField is supported at the moment, got " + field.Type()) |
| 1585 | } |
| 1586 | |
| 1587 | for _, refRecord := range refRecords { |
| 1588 | ids := refRecord.GetStringSlice(relField.Name) |
| 1589 | |
| 1590 | // unset the record id |
| 1591 | for i := len(ids) - 1; i >= 0; i-- { |
| 1592 | if ids[i] == mainRecord.Id { |
| 1593 | ids = append(ids[:i], ids[i+1:]...) |
| 1594 | break |
| 1595 | } |
| 1596 | } |
| 1597 | |
| 1598 | // cascade delete the reference |
| 1599 | // (only if there are no other active references in case of multiple select) |
| 1600 | if relField.CascadeDelete && len(ids) == 0 { |
| 1601 | if err := app.Delete(refRecord); err != nil { |
| 1602 | return err |
| 1603 | } |
| 1604 | // no further actions are needed (the reference is deleted) |
| 1605 | continue |
| 1606 | } |
| 1607 | |
| 1608 | if relField.Required && len(ids) == 0 { |
| 1609 | return fmt.Errorf("the record cannot be deleted because it is part of a required reference in record %s (%s collection)", refRecord.Id, refRecord.Collection().Name) |
| 1610 | } |
| 1611 | |
| 1612 | // save the reference changes |
| 1613 | // (without validation because it is possible that another relation field to have a reference to a previous deleted record) |
| 1614 | refRecord.Set(relField.Name, ids) |
| 1615 | if err := app.SaveNoValidate(refRecord); err != nil { |
| 1616 | return err |
| 1617 | } |
| 1618 | } |
| 1619 | |
| 1620 | return nil |
| 1621 | } |
no test coverage detected
searching dependent graphs…