Skip to content

Containers

Derevtsov Konstantin edited this page Jul 10, 2020 · 4 revisions

D3 provides two special containers - wrappers on single and multiple entities. They have a similar interface as GO default container (like slice). D3 requests these containers for implementing some features (like lazy/eager loading). Currently there 2 containers:

  • Collection - use it to store multiple entities, for example, in many_to_many relations.
  • Cell - use it for store single entity, for example, in one_to_one relations.

For working with relation you must create containers, not slice (but you can use it as a slice in future). For example, create a new user with photos and profile:

//d3:entity
//d3_table:users
type User struct {
	Id      sql.NullInt32      `d3:"pk:auto"`
	// use *entity.Collection or *entity.Cell as field type
	Photos  *entity.Collection `d3:"one_to_many:<target_entity:myModule/myPackage/Photo,join_on:user_id,delete:nullable>,type:lazy"`
	Profile *entity.Cell       `d3:"one_to_one:<target_entity:myModule/myPackage/Profile,join_on:profile_id,delete:cascade>,type:lazy"`
	Name    string
}

// use entity.NewCollection and entity.NewCell for create instances of collection and cell.
user := &User{
	Photos: entity.NewCollection(&Photo{
			Src:    "http://photo1",
		}, &Photo{
			Src:    "http://photo1",
		}),
	Profile: entity.NewCell(&Profile{
		Description: "this is good user",
	}),
	Name: "d3-user",
}

repository.Persists(ctx, user)

Working with containers

For more information about container methods, look at entity.Cell and entity.Collection documentation.

Clone this wiki locally