This is a creation in Article, where the information may have evolved or changed.
Models.go
============================
Package Main
Import (
"Github.com/astaxie/beego/orm"
)
Type User struct {
Id int
Name string
Profile *profile ' orm: "rel (one)" '//Onetoone relation
}
Type profile struct {
Id int
Age Int16
User *user ' orm: ' Reverse (one) ' '//Set inverse relationship (optional)
}
Func init () {
You need to register the defined model in Init
Orm. Registermodel (new User), new (profile)
}
Main.go
==============
Package Main
Import (
"FMT"
"Github.com/astaxie/beego/orm"
_ "Github.com/go-sql-driver/mysql"
)
Func init () {
Orm. Registermodel (New User)
Orm. RegisterDatabase ("Default", "MySQL", "Ta3:ta3@/ta3?charset=utf8")
Orm. RUNSYNCDB ("Default", False, True)//true to False, if the table exists will give a hint, if changed to False will not prompt, this sentence does not report the primary key does not exist error
}
Func Main () {
o: = orm. Neworm ()
O.using ("Default")//default is used, you can specify as a different database
User: = User{id:1}
ERR: = O.read (&user)
If Err = = orm. errnorows {
Fmt. PRINTLN ("Query not reached")
} else If Err = = orm. ERRMISSPK {
Fmt. PRINTLN ("PRIMARY key not Found")
} else {
Fmt. Println (user. Id, user. Name)
}
}
Execution Result:
CREATE table ' user '
-- --------------------------------------------------
--Table Structure for ' main. User '
-- --------------------------------------------------
CREATE TABLE IF not EXISTS ' user ' (
' id ' integer auto_increment not NULL PRIMARY KEY,
' Name ' varchar (255) is not NULL,
' profile_id ' integer not NULL UNIQUE
) Engine=innodb;
CREATE TABLE ' profile '
-- --------------------------------------------------
--Table Structure for ' main. Profile '
-- --------------------------------------------------
CREATE TABLE IF not EXISTS ' profile ' (
' id ' integer auto_increment not NULL PRIMARY KEY,
' Age ' smallint not NULL
) Engine=innodb;
Query not reached
Second re-execution:
Table ' user ' already exists, skip
Table ' profile ' already exists, skip
Query not reached
If Orm. RUNSYNCDB ("Default", False, True) is changed to ORM. RUNSYNCDB ("Default", False, False)
The execution result is not prompted.