在 activerecord 中包含自引用模型,并根据包含的模型从两者中进行选择

发布于 2024-12-09 07:38:21 字数 739 浏览 0 评论 0原文

对于相当令人困惑的标题表示歉意,我发现很难正确地表达这个问题。

我有一个模型,将其称为 Thing,即 has_many :lated_thingshas_many :linked_dateshas_many :assignments (用户分配给事物)。我想进行一个查询来选择用户分配到的事物中的所有关联日期,以及相关事物中的所有关联日期。

目前,我有这个方法可以获取直接分配的关联日期:

AssociatedDate.includes(:thing)
   .includes(:thing => :assignments)
   .where('assignments.user_id' => id)

但是,我尝试加载通过 :lated_things 相关的日期的尝试未加载。我得到的最接近的只是在查询中包含 :lated_things

AssociatedDate.includes(:thing)
   .includes(:thing => [:assignments, :related_things])
   .where('assignments.user_id' => id)

但是我不知道从那里去哪里,并且它本身不会对查询的结果产生任何影响询问。我想要的选择是否可能,我将如何去做?

Apologies for the rather confusing title, I'm finding it rather difficult to phrase this question properly.

I have a model, call it Thing that has_many :related_things, has_many :associated_dates and has_many :assignments (users assigned to things). I want to make a single query to select all associated dates from a Thing which a user is assigned to, as well as all associated dates from the related things.

At the moment, I have this which works for getting the associated dates which are directly assigned:

AssociatedDate.includes(:thing)
   .includes(:thing => :assignments)
   .where('assignments.user_id' => id)

However, my attempts to also load those dates that are related through :related_things are not loaded. The closest I've got is just including the :related_things in the query:

AssociatedDate.includes(:thing)
   .includes(:thing => [:assignments, :related_things])
   .where('assignments.user_id' => id)

But then I don't know where to go from there and on its own this does not have any effect on the outcome of the query. Is the select I want possible, and how would I go about doing it?

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

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

发布评论

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

评论(1

吐个泡泡 2024-12-16 07:38:21

我认为你需要加入。请查看此处的文档。

类似于AssociatedDate.joins(:thing).joins(:thing=>:lated_thing)

I think you need joins. Have a look at the documentation here.

Something like AssociatedDate.joins(:thing).joins(:thing=>:related_thing)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文