如何使用m2m条件查询数据

这是两个具有许多关系的模型。 现在,我想按类别名称查询主题。 我知道我可以通过原始SQL来实现此目的,例如 select * from topic where id IN(从topic_categories中的topic_id中选择category_id IN(从名称为ILIKE'%tech%'的类别中选择id)); </ code> </ p>

问题是,如何使用gorm以更高的性能和更易读的方式执行此操作。</ p>

  type类别结构{
名称字符串
}

type主题结构{
名称字符串
类别[] *类别gorm:“ manytomany; topic_categories”
}
</ code> </ pre>
</ div>

展开原文

原文

Here is the two model with manytomany relationship. Right now I want to query the topic by category name. I know I could achieve this by raw sql like select * from topic where id IN (SELECT topic_id from topic_categories where category_id IN (select id from category where name ILIKE '%tech%'));

The question is, how to do this with gorm in a higher performance and more readable way.

type Category struct {
  Name string
}

type Topic struct {
  Name string
  Categories []*Category `gorm:"manytomany;topic_categories"`
}

1个回答



我认为GORM的文档写得很好。 您可以在这里找到答案
http://gorm.io/docs/many_to_many.html
或者您可以这样做</ p>

  db.Tabel(“ topic”)。Select(“ *”)。Where(“ id IN(从topic_categories中选择topic_id,其中category_id  IN(从名称为ILIKE'%?%')的类别中选择ID)“,” tech“)
</ code> </ pre>
</ div>

展开原文

原文

I think documentation of GORM is written very well. You can find answer is here http://gorm.io/docs/many_to_many.html Or you can do like this

db.Tabel("topic").Select("*").Where("id IN (SELECT topic_id from topic_categories where category_id IN (select id from category where name ILIKE '%?%'))","tech")

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐