Get data from two different struct

Issue

Have this struct of User and Post and I try to make Name from User to be included within Post Struct when a user create a new post.

type User struct {
    ID             int
    Name           string
    Created        time.Time
}

type Post struct {
    ID int
    PostTitle string
    PostDesc string
    Created time.Time
}

How can I create something connected between this two struct such as Author of the Post ?

The goal is try to get the name of the post author which from User struct with the code below:

post, err := app.Models.Posts.GetPost(id)

GetPost() just run SELECT query and scan row

Solution

This approach is without any ORM.
It’s a simple query that can return multiple rows. You’ve to scan the whole resultset and map each column on the struct’s fields.

Keep in mind to always check for errors.

Below you can find the solution:

package main

import (
    "database/sql"
    "fmt"
    "time"

    _ "github.com/lib/pq"
)

type Post struct {
    ID        int
    PostTitle string
    PostDesc  string
    Created   time.Time
    UserID    int
    User      User
}

type User struct {
    ID      int
    Name    string
    Created time.Time
}

func main() {
    conn, err := sql.Open("postgres", "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable")
    if err != nil {
        panic(err)
    }
    defer conn.Close()

    rows, err := conn.Query(`SELECT posts.id, post_title, post_desc, posts.created, users.id, users.name, users.created FROM posts INNER JOIN users ON posts.user_id=users.id`)
    if err != nil {
        panic(err)
    }

    var posts []Post
    for rows.Next() {
        var post Post
        if err = rows.Scan(&post.ID, &post.PostTitle, &post.PostDesc, &post.Created, &post.User.ID, &post.User.Name, &post.User.Created); err != nil {
            panic(err)
        }
        posts = append(posts, post)
    }

    if err = rows.Err(); err != nil {
        panic(err)
    }

    for _, v := range posts {
        fmt.Printf("author name: %q\n", v.User.Name)
    }
}

Let me know if this helps.

Answered By – Ivan Pesenti

Answer Checked By – Dawn Plyler (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.