在多个嵌套的Eager加载关联上指定条件(Specifying Conditions on Multiple Nested Eager Loaded Associations)

编程入门 行业动态 更新时间:2024-10-12 18:15:43
多个嵌套的Eager加载关联上指定条件(Specifying Conditions on Multiple Nested Eager Loaded Associations)

我试图在ActiveRecord上查询多个嵌套的eager加载关联,其条件如下:

user.books.includes(slot: [room: :school]).where("books.slot.room.school.id = 1")

显然这个查询是错误的,但基本上我想要达到的是某个学校的user.books关系。

我的模型结构是:

class User < ActiveRecord::Base has_many :books has_many :slots, through: :books has_many :rooms, through: :slots has_many :schools end class Book < ActiveRecord::Base belongs_to :user belongs_to :slot end class Slot < ActiveRecord::Base has_many :books belongs_to :room end class Room < ActiveRecord::Base belongs_to :school has_many :slots end class School < ActiveRecord::Base has_many :users has_many :rooms has_many :slots, through: :rooms has_many :books, through: :slots end

有任何想法吗? 提前致谢。

I'm trying to query on ActiveRecord multiple nested eager loaded associations with conditions like so:

user.books.includes(slot: [room: :school]).where("books.slot.room.school.id = 1")

Obviously this query is wrong, but basically what I'm trying to reach is a relation of user.books for a certain school.

My model structure is:

class User < ActiveRecord::Base has_many :books has_many :slots, through: :books has_many :rooms, through: :slots has_many :schools end class Book < ActiveRecord::Base belongs_to :user belongs_to :slot end class Slot < ActiveRecord::Base has_many :books belongs_to :room end class Room < ActiveRecord::Base belongs_to :school has_many :slots end class School < ActiveRecord::Base has_many :users has_many :rooms has_many :slots, through: :rooms has_many :books, through: :slots end

Any ideas? Thanks in advance.

最满意答案

includes预先加载关联记录,而joins则执行您想要执行的操作。

这个问题已在这里被多次提出。 在你问一个问题之前,请确保你看起来并尝试在这里找到类似的问题。

所以你想改变你的代码:

user.books.joins(slot: [room: :school]).where(schools: { id: 1 })

includes eager loads association records, while joins does what you want to do.

This question has been asked here numerous times. Please make sure that you look and try to find a similar question here before you ask one.

So you want to change your code like this:

user.books.joins(slot: [room: :school]).where(schools: { id: 1 })

更多推荐

本文发布于:2023-07-14 18:59:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1106702.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   嵌套   加载   条件   Eager

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!