查询不存在的 habtm 记录

发布于 2024-12-22 23:15:07 字数 179 浏览 3 评论 0原文

抱歉初学者的问题。 我在资产和项目之间有 habtm 关系。假设我正在循环遍历所有资产,我想找到与该资产无关的所有项目,但这不起作用:

Project.includes(:assets).where("assets.id != ?", asset.id)

正确的查询是什么?

sorry for the beginner's question.
I have habtm relationship between Assets and Projects. Assuming I'm looping thru all Assets I want to find all Projects not associated with this Asset, but this doesn't work:

Project.includes(:assets).where("assets.id != ?", asset.id)

what is the proper query?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

燕归巢 2024-12-29 23:15:07

如果您想查找与特定资产不关联的所有项目,类似这样的操作应该可行(未经测试,因此请根据需要进行调整):

Project.joins(:assets_projects).where("assets_projects.asset_id != ?", asset_id)

asset_id 是资产实例的 id

另外,您不应该循环遍历资产来查找与迭代当前资产关联的所有项目,这意味着太多的数据库调用(这是所谓的 N+1 问题 - 可以找到一个很好的解释,例如 此处)。要仅通过一个查询查找与任何资产不关联的所有项目,请执行以下操作:

Project.find_by_sql(%(
  SELECT * FROM projects
  WHERE NOT EXISTS (SELECT * FROM assets_projects WHERE assets_projects.project_id = projects.id)
))

If you want to find all Projects not associated with a particular Asset, something like this should work (it's untested so adjust as needed):

Project.joins(:assets_projects).where("assets_projects.asset_id != ?", asset_id)

asset_id is the id of your Asset instance.

Also, you should not loop through the Assets to find all Projects associated with the iteration's current asset, that would mean too many database calls (it's the so called N+1 problem - a good explanation can be found eg here). To find all Projects not associated with any Asset with just one query, do this:

Project.find_by_sql(%(
  SELECT * FROM projects
  WHERE NOT EXISTS (SELECT * FROM assets_projects WHERE assets_projects.project_id = projects.id)
))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文