Skip to content

Sqlite subpackage: best practice to create associated data #70

Answered by benbjohnson
luzzi8 asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @luzzi8. Good question and sorry for the delay getting back to you. For creation, I would use the helper functions (e.g. createAddress()) within the CreatePerson() method:

func (s *PersonService) CreatePerson(ctx context.Context, person *wtf.Person) error {
	tx, err := s.db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	// Create root person object here.
	if err := createPerson(ctx, tx, person); err != nil {
		return err
	}

	// Loop over associated addresses and create them here.
	for _, address := range person.Addresses {
		address.PersonID = person.ID // associate one-to-many relationship here.
		if err := createAddress(ctx, tx, address); err != nil {
			r…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by benbjohnson
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants