-
Notifications
You must be signed in to change notification settings - Fork 6
Entities
Piotr Kowalczuk edited this page Sep 6, 2018
·
5 revisions
Entity is the most important part of the generated code. It reflects structure of the table and it relationships.
Each entity gets name in format <TableName>Entity
.
For example, such definition of table:
_ = pqt.NewTable("news").
AddColumn(pqt.NewColumn("id", pqt.TypeSerial())).
AddColumn(pqt.NewColumn("title", pqt.TypeText(), pqt.WithNotNull())).
AddColumn(pqt.NewColumn("lead", pqt.TypeText())).
AddColumn(pqt.NewColumn("content", pqt.TypeText(), pqt.WithNotNull())).
AddColumn(pqt.NewColumn("created_at", pqt.TypeTimestampTZ(), pqt.WithNotNull()))
AddColumn(pqt.NewColumn("updated_at", pqt.TypeTimestampTZ()))
will produce such entity struct:
type NewsEntity struct{
ID int64
Title string
Content sql.NullString
Content string
CreatedAt time.Time
UpdatedAt pq.NullTime
}
As we can see the code generated for the column that is null-able is different.
The library is using Null
types that are coming from sql and pq package.
Entity can be aware of relationships it belongs to. To create extra properties that can hold related object(s) WithBidirectional() should be passed to the relationship definition e.g.:
news := pqt.NewTable("news")
comment := pqt.NewTable("comment")
comment.AddRelationship(pqt.ManyToOne(news, pqt.WithBidirectional()))
Such definition will produce code similar to this:
type NewsEntity struct{
Comments []*CommentEntity
}
type CommentEntity struct {
News *NewsEntity
}
Those properties are not populated automatically. To know more about making queries with joins visit this page.