基于child属性的关联查询
Association query based on child attribute
如果 'state' 与 'approved' 不同,我如何获得所有没有 children 的 parents 或 children?
Parent.includes(:children).where.not(children: { status: 'approved' })
"SELECT \"parents\".* FROM \"parents\" INNER JOIN \"children\" ON "children\".\"parent_id\" = \"parents\".\"id\" WHERE \"children\".\"state\" = 'approved'"
它 returns 只有 parents 与 children 和 status
不同于 approved
但忽略 parents 没有 children
Parent.includes(:children).where(children: { id: nil })
"SELECT \"parents\".\"id\" AS t0_r0, \"parents\".\"date\" AS t0_r1, ........, \"parents\".\"slug\" AS t0_r33, \"children\".\"id\" AS t1_r0, \"children\".\"parent_id\" AS t1_r1, \"children\".\"request_state\" AS t1_r8 FROM \"parents\" LEFT OUTER JOIN \"children\" ON \"children\".\"edition_id\" = \"parents\".\"id\" WHERE \"children\".\"id\" IS NULL"
只有returns parents 没有children
所以你需要把两个条件一起加入。
由于includes
只支持where
子句中的hash like条件,所以我们需要使用references
to write the condition in SQL source
Using where like this will only work when you pass it a Hash. For
SQL-fragments you need use references to force joined tables
Parent.includes(:children).where("children.status <> 'approved' OR children.id IS NULL").references(:children)
试一试
如果 'state' 与 'approved' 不同,我如何获得所有没有 children 的 parents 或 children?
Parent.includes(:children).where.not(children: { status: 'approved' })
"SELECT \"parents\".* FROM \"parents\" INNER JOIN \"children\" ON "children\".\"parent_id\" = \"parents\".\"id\" WHERE \"children\".\"state\" = 'approved'"
它 returns 只有 parents 与 children 和 status
不同于 approved
但忽略 parents 没有 children
Parent.includes(:children).where(children: { id: nil })
"SELECT \"parents\".\"id\" AS t0_r0, \"parents\".\"date\" AS t0_r1, ........, \"parents\".\"slug\" AS t0_r33, \"children\".\"id\" AS t1_r0, \"children\".\"parent_id\" AS t1_r1, \"children\".\"request_state\" AS t1_r8 FROM \"parents\" LEFT OUTER JOIN \"children\" ON \"children\".\"edition_id\" = \"parents\".\"id\" WHERE \"children\".\"id\" IS NULL"
只有returns parents 没有children
所以你需要把两个条件一起加入。
由于includes
只支持where
子句中的hash like条件,所以我们需要使用references
to write the condition in SQL source
Using where like this will only work when you pass it a Hash. For SQL-fragments you need use references to force joined tables
Parent.includes(:children).where("children.status <> 'approved' OR children.id IS NULL").references(:children)
试一试