Relationships

For querying relationships, you can use QuerySeter or QueryM2Mer

For example:

  1. o := orm.NewOrm()
  2. post := Post{Id: 1}
  3. m2m := o.QueryM2M(&post, "Tags")
  4. // In the first param object must have primary key
  5. // The second param is the M2M field will work with
  6. // API of QueryM2Mer will used to Post with id equals 1

Full API:

QueryM2Mer Add

  1. tag := &Tag{Name: "golang"}
  2. o.Insert(tag)
  3. num, err := m2m.Add(tag)
  4. if err == nil {
  5. fmt.Println("Added nums: ", num)
  6. }

Add accepts Tag,*Tag,[]*Tag,[]Tag,[]interface{}

  1. var tags []*Tag
  2. ...
  3. // After reading tags
  4. ...
  5. num, err := m2m.Add(tags)
  6. if err == nil {
  7. fmt.Println("Added nums: ", num)
  8. }
  9. // It can pass multiple params
  10. // m2m.Add(tag1, tag2, tag3)

QueryM2Mer Remove

Remove tag from M2M relation:

Remove supports many types: Tag Tag []Tag []Tag []interface{}

  1. var tags []*Tag
  2. ...
  3. // After reading tags
  4. ...
  5. num, err := m2m.Remove(tags)
  6. if err == nil {
  7. fmt.Println("Removed nums: ", num)
  8. }
  9. // It can pass multiple params
  10. // m2m.Remove(tag1, tag2, tag3)

QueryM2Mer Exist

Test if Tag is in M2M relation

  1. if m2m.Exist(&Tag{Id: 2}) {
  2. fmt.Println("Tag Exist")
  3. }

QueryM2Mer Clear

Clear all M2M relation:

  1. nums, err := m2m.Clear()
  2. if err == nil {
  3. fmt.Println("Removed Tag Nums: ", nums)
  4. }

QueryM2Mer Count

Count the number of Tags:

  1. nums, err := m2m.Count()
  2. if err == nil {
  3. fmt.Println("Total Nums: ", nums)
  4. }