gpt4 book ai didi

ruby-on-rails - 在相关列上排序

转载 作者:行者123 更新时间:2023-11-29 14:26:47 25 4
gpt4 key购买 nike

我有 Model has_many ModelItemsModelItems belongs_to OtherModel 具有“代码”列。

我想做这样的事情:

Model.find(1).model_items.includes(:other_model).order("other_model.code" :desc)

我正在尝试根据相关代码列的文本进行排序。

我什至尝试过:

ModelItems.where(model_id: 1).includes(:other_model).order("other_model.code" :desc)

我知道我需要在此处包含或加入,但无论我做什么,我都会遇到此错误的变体:

PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "other_model"

更新

这是一个不使用真实模型名称的例子。我一直都是对的。

include 是单数,订单模型名称需要是复数 - 为了清楚起见,让我们将 other_model 更改为 widgit:

Model.find(1).model_items.includes(:widgit).order("widgits.code ASC")

最佳答案

includes 在此上下文中将执行 2 个查询以创建一个伪外连接(也称为 preload),其概念如下

 SELECT * FROM model_items WHERE model_items.model_id = 1

SELECT * FROM other_models WHERE other_models.model_item_id IN ( [IDS FROM PREVIOUS QUERY])

您可以通过几种方式强制执行单个查询:

  • eager_load - (ModelItems.eager_load(:other_model)) 当您引用连接表时,这就是 includes 的工作方式在哈希查找器查询条件中或添加 references 时。

  • references - (ModelItems.includes(:other_model).references(:other_model)) 这会强制执行 eager_load 路径包含

  • where 哈希查找器方法 (ModelItems.includes(:other_model).where(other_models: {name: 'ABC'})) 这里 includes 智能地意识到您已经为与 other_model 的关系设置了条件,并且会自动创建连接,这样查询就不会出现格式错误。然而,这种查询表示为外连接,但执行起来像内连接,效率较低 *

但是,如果您不需要 other_model 中的信息,而只想将其用作排序机制,那么您可以使用 joins (INNER JOIN) 或 left_joins (OUTER JOIN) 这将允许您对这些数据进行排序,但不会检索属性或实例化 other_model 关系下的任何相关对象

 ModelItems.joins(:other_model)
# OR
ModelItems.left_joins(:other_model)

*这些选项可以组合使用,在 includes where 散列查找器方法的情况下,我总是推荐以下 ModelItems.joins(:other_model ).includes(:other_model).where(other_models: { name: 'ABC'}) (INNER JOIN)。这将返回与 ModelItems.includes(:other_model).where(other_models: {name: 'ABC'}) 相同的数据集(LEFT OUTER JOIN)但是通过使用 INNER JOIN 它变得更高效比它的 LEFT OUTER JOIN 版本

旁注 order("other_models.code":desc) 这是无效的。相反,您需要在 String 中包含顺序方向,或者使 StringSymbol 例如(("other_models.code DESC")("other_models.code": :desc))

关于ruby-on-rails - 在相关列上排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57008094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com