summaryrefslogtreecommitdiffstats
path: root/internal/models/operation.go
diff options
context:
space:
mode:
authorMatthew Lemon <y@yulqen.org>2024-02-11 20:37:53 +0000
committerMatthew Lemon <y@yulqen.org>2024-02-11 20:37:53 +0000
commit21ec508717ecd6112984b56ca376ebac11477a2a (patch)
tree89f1b56a76c2ca6cb91be463924bd8563a9a20f0 /internal/models/operation.go
parent9d18b9e9d9ab7561deadc867654f7cc4db15d2e1 (diff)
Have added a listAll handler for new operation model
This is the first attempt at querying a table with a foreign key relation and returning the result to be used in Go code. Learned quite a bit! Including getting a null pointer error because I forgot to initialise the sql.DB in the application structure.
Diffstat (limited to '')
-rw-r--r--internal/models/operation.go43
1 files changed, 38 insertions, 5 deletions
diff --git a/internal/models/operation.go b/internal/models/operation.go
index 8547030..abb874c 100644
--- a/internal/models/operation.go
+++ b/internal/models/operation.go
@@ -2,15 +2,48 @@ package models
import (
"database/sql"
+ "time"
)
type Operation struct {
- ID int
- Name string
- Description string
- Organisation Organisation
+ ID int
+ Name string
+ Description string
+ Created time.Time
+ OrganisationName string
}
-type OperationMOdel struct {
+type OperationModel struct {
DB *sql.DB
}
+
+func (m *OperationModel) ListAll() ([]Operation, error) {
+
+ stmt := `SELECT op.id, op.name, op.description, op.created, org.name FROM operations op INNER JOIN organisations org ON op.organisation_id=org.id`
+
+ // stmt := `SELECT * FROM operations`
+
+ rows, err := m.DB.Query(stmt)
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+
+ var ops []Operation
+
+ for rows.Next() {
+ var o Operation
+ err = rows.Scan(&o.ID, &o.Name, &o.Description, &o.Created, &o.OrganisationName)
+ if err != nil {
+ return nil, err
+ }
+
+ ops = append(ops, o)
+ }
+
+ if err = rows.Err(); err != nil {
+ return nil, err
+ }
+ return ops, err
+}