簡體   English   中英

活動記錄:如何基於與指定屬性沒有關聯的父項來查找父項

[英]Active Record: How to find a Parent based on an that there is no association with a given attribute

我具有以下數據庫結構:

Parent
 -> child 1
 -> child 2
 ->.. 

現在,我要查找所有沒有將特定屬性設置為true的孩子的父母。

例:

Should not be found: 
Parent: 
 -> child 1 (selected: true)
 -> child 2 (selected: false)

Should be found
Parent: 
 -> child 1 (selected: nil)
 -> child 2 (selected: false)

目前,我有以下內容:

Project.all - Project.includes(:project_images).where(project_images: { selected: true })

這可以正常工作,但似乎效率低下。 我相信應該有一個更簡便,更快捷的方法。

您可以只使用where.not解決它。

參見https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods/WhereChain.html#method-i-not

Project.joins(:project_images).where.not(project_images: { selected: true })
    parents = Parent.joins(:children).where('children.selected = FALSE or children.selected is NULL')

此查詢從選擇屬性未設置為true的父子內部聯接表中選擇行。

如果希望父對象甚至沒有關聯的子代,則必須保留外部聯接子代。

Parent.joins('left join children on parents.id = childrenparent_id')..where('children.selected = FALSE or children.selected is NULL')

Project.joins(:project_images).where(“ project_images.selected NOT IN(TRUE)”);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM