Using association queries in Beego (join query)
- Document URL: here
//使用实例:article:=new(Article)num,err:= o.QueryTable("go_article").RelatedSel().All(&article)
- However, the direct use of Relatedsel () is not possible and must first be defined in model:
type User struct { Id int Name string Age int}type Article stuct { Id int Title string Content string User *User `orm:"rel(fk)"` //这样写,默认在Article中应该有一个user_id的字段,如果没有,通过beego自动建表的话,它会生成;如果是手动建表,记得把user_id 这个字段加上去}
Define the table field as "rel (FK)", which is the foreign key, and to define other types, see the document.
- Command line auto-build table:
orm.RunCommand() //main函数或init函数中需要加这行代码,否则不能自动建表
go build main.go #先在命令行中执行这句,会生成main.exe文件./main orm syncdb -h #-h会提示可用的参数./main orm syncdb -v #建表的同时会显示建表的sql语句
If using the automatic table, it is recommended not to write the int,string directly as above, the specific Field field method, see the document
In fact, the main purpose of my use of the command line is to find out what field name the user in article generates, and the result is user_id, and it has nothing to do with the prefix of your user table name.
- Questions:
4.1 Relatedsel () can choose "Field name" Relatedsel ("user") in fact, just choose "Table name" (not actually the table name, but the corresponding field in the struct lowercase), only when a model in the use of multiple REL fields is meaningful. But how do you choose the specified field in the associated user table?
4.2 Relatedsel () The default should be inner join, but I want to be a left join, what should I write?
4.3 I want to see the SQL statements that are used every time the database operation is performed, how can I view them?
- A little emotion:
Personally feel that Beego comes with the ORM is actually very bad use, and some concepts are not understood.
As a code farmer who often writes thinkphp 3.2, it really feels too troublesome to use other frames of the ORM.
But what advantage does ORM have? In fact, I always do not understand, tp3.2 operation of the database method really good is not its ORM, but its coherent operation is really comfortable to write.
In fact, Beego's author has also done a separate ORM usage and tp3.2 is still a bit like.
But GitHub can search the most star go ORM should be gorm, look at the document, found that its usage is actually very similar to the tp3.2, I still prefer to use Gorm.