2016-11-07 77 views
1

我有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 

FormField

belongs_to :form, Form 
belongs_to :field, Field 

條件

我想編寫一個查詢來獲取每一個領域內,其idfieldsconditions(常見的兩種Form & Field)沿着已知的形式

例如:以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這非常直。但是我的情況與此稍有不同。請看看這兩個問題,並幫助我克服這一步。

+0

你有沒有嘗試從文檔(https://hexdocs.pm/ecto/Ecto.Query.html#preload/3)? – Dogbert

+0

[Preload all Relationships]的可能重複(http://stackoverflow.com/questions/33710272/preload-all-relationships) – michalmuskala

+0

@Dogbert是的,我查看了文檔。但我無法達到我想要的 –

回答

0

對不起。下面的查詢工作

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