【问题标题】:Preload nested associations in ecto在ecto中预加载嵌套关联
【发布时间】:2016-11-08 02:11:36
【问题描述】:

我有 4 个模型,它们关联为

表格

has_many :form_fields, FormField, on_delete: :delete_all
has_many :fields, through: [:form_fields, :field]
has_many :conditions, Condition, on_delete: :delete_all

字段

has_many :form_fields, FormField, on_delete: :delete_all
has_many :forms, through: [:form_fields, :form]
has_many :conditions, Condition, on_delete: :delete_all

表单域

belongs_to :form, Form
belongs_to :field, Field

条件

belongs_to :field, Field
belongs_to :form, Form

我想编写一个查询来获取一个表单,其 id 以及 fieldsconditionsFormField 都在每个字段中都很常见)

例如:得到一个id为1的表格,

%{
    id: 1,
    fields: [
        %{
            id: 1,
            conditions: [
                %{
                    id: 1
                    form_id: 1,
                    field_id: 1
                },
                %{
                    id: 2
                    form_id: 1,
                    field_id: 1
                }
            ]
        },
        %{
            id: 2,
            conditions: [
                %{
                    id: 3
                    form_id: 1,
                    field_id: 2
                },
                %{
                    id: 4
                    form_id: 1,
                    field_id: 2
                }
            ]
        }
    ]
}

我的问题被标记为可能与another question 重复,这非常直截了当。但我的情况与此略有不同。请看一下这两个问题并帮助我克服这一步。

【问题讨论】:

标签: elixir ecto


【解决方案1】:

对不起各位。以下查询有效

form_conditions =
  Condition
  |> where(form_id: ^id)
form =
  Form
  |> where(id: ^id)
  |> preload(fields: [conditions: ^form_conditions])
  |> Repo.one!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多