Skip to content

Instantly share code, notes, and snippets.

@wyattjoh
Last active January 20, 2016 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wyattjoh/850c56c8526a10300af2 to your computer and use it in GitHub Desktop.
Save wyattjoh/850c56c8526a10300af2 to your computer and use it in GitHub Desktop.
package main
import (
"log"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)
type Image struct {
ID uint64
URL string
}
type User struct {
ID uint64
ProfileImageID uint64 `gorm:"column:profile_image"`
ProfileImage Image
}
var schema = `
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS images;
CREATE TABLE images(
id BIGINT PRIMARY KEY,
url TEXT
);
CREATE TABLE users(
id BIGINT,
profile_image BIGINT,
FOREIGN KEY(profile_image) REFERENCES images(id)
);
INSERT INTO images(id, url) VALUES(1, 'http://example.com/image_1.jpg');
INSERT INTO images(id, url) VALUES(2, 'http://example.com/image_2.jpg');
INSERT INTO users(id, profile_image) VALUES(1, 1);
INSERT INTO users(id, profile_image) VALUES(2, 2);
`
func main() {
db, _ := gorm.Open("sqlite3", "test.db")
db.LogMode(true)
if err := db.Exec(schema).Error; err != nil {
log.Fatal(err)
}
var users []User
if err := db.Table("users").Preload("ProfileImage").Find(&users).Error; err != nil {
log.Fatal(err)
}
log.Printf("Users: %v", users)
}
package main
import (
"log"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
)
type Image struct {
ID uint64
URL string
}
type User struct {
ID uint64
ProfileimageID uint64 `gorm:"column:profile_image"`
Profileimage Image
}
var schema = `
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS images;
CREATE TABLE images(
id BIGINT PRIMARY KEY,
url TEXT
);
CREATE TABLE users(
id BIGINT,
profile_image BIGINT,
FOREIGN KEY(profile_image) REFERENCES images(id)
);
INSERT INTO images(id, url) VALUES(1, 'http://example.com/image_1.jpg');
INSERT INTO images(id, url) VALUES(2, 'http://example.com/image_2.jpg');
INSERT INTO users(id, profile_image) VALUES(1, 1);
INSERT INTO users(id, profile_image) VALUES(2, 2);
`
func main() {
db, _ := gorm.Open("sqlite3", "test_works.db")
db.LogMode(true)
if err := db.Exec(schema).Error; err != nil {
log.Fatal(err)
}
var users []User
if err := db.Table("users").Preload("Profileimage").Find(&users).Error; err != nil {
log.Fatal(err)
}
log.Printf("Users: %v", users)
}
CREATE TABLE images(
id BIGINT PRIMARY KEY,
url TEXT
);
CREATE TABLE users(
id BIGINT,
profile_image BIGINT,
FOREIGN KEY(profile_image) REFERENCES images(id)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment