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) 解决方法
真的,作为一种关系会更好.认为这样可行:
@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') (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |