D
D
Denis Dolmatov2018-11-11 13:25:45
PostgreSQL
Denis Dolmatov, 2018-11-11 13:25:45

How to properly bind models in golang?

Tell me how to handle cookies and save the article with the owner.

PostgreSQL
create table users(
id varchar(64) primary key, username varchar(64) not null,
password VARCHAR(64));
create table article(
id varchar(64) Primary key,
name Varchar(64),
user_id VARCHAR(64) REFERENCES Users(id));
Modelb
type Article struct {
Id string
Name string
User_*User
}
Recording to the database
func CreateArticle(name string, user *User) (int64, error) {
id, _ := uuid.NewV4()
result, _ := db.Exec("INSERT INTO articles VALUES($1, $2, $3)", id, name, user)
rowsAffected, err := result.RowsAffected()
return rowsAffected, nil
}
Article save function
func NewArticle(w http.ResponseWriter, r *http.Request) {
session, _ := store.Get(r, "cookie-name")
name := r.FormValue("name")
owner := session.Values["username"]
// При проверке типа owner показывает стринг выдает юззернейм
user, _ := models.GetUser(owner) Определяется как интерфейс
rowsAffected, err := models.CreateArticle(name, description, images, price, user)
}
User in the database
func GetUser(username string)(*User, error) {
row := db.QueryRow("SELECT * FROM users WHERE username=$1", username)
fmt.Println(row)
user := new(User)
err := row.Scan(&user.Id, &user.Username, &user.Password)
if err != nil {
return nil, err
}
return user, nil
}

Kindly help in this matter and also throw off a couple of code examples or whole works of articles very much appreciated!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rxecore, 2018-11-12
@rxecore

If I understand the question correctly then
article := new(Article)
user := new(User)
article.User = append(article.User,user)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question