加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何通过与Active Record关联找到has_many中缺

发布时间:2020-12-16 22:41:47 所属栏目:百科 来源:网络整理
导读:我们有“主题 – 关系 – 类别”. 也就是说,主题通过关系有很多类别. 我认为很容易得到一个类别的主题 #Relationship Model Topic_id: integer Category_id: integer @topics=Topic.joins(:relationships) 但是,并非每个主题都有一个类别.那么我们如何检索没
我们有“主题 – 关系 – 类别”.

也就是说,主题通过关系有很多类别.

我认为很容易得到一个类别的主题

#Relationship  Model
  Topic_id: integer
  Category_id: integer

  @topics=Topic.joins(:relationships)

但是,并非每个主题都有一个类别.那么我们如何检索没有类别的主题呢?
是否有减号查询?

也许它看起来像@ topics = Topic.where(‘id NOT IN(?)’,Relationship.all)
我在activerecord equivalent to SQL ‘minus’找到它但不确定这个解决方案.

解决方法

真的,作为一种关系会更好.认为这样可行:
@topics = Topic.joins('left join relationships on relationships.topic_id = topics.id').where('relationships.category_id is null')

或这个:

@topics = Topic
    .joins('left join relationships on relationships.topic_id = topics.id join categories on categories.id = relationships.category_id')
    .group('topics.id').having('count(categories.id) = 0')

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读