I have two ecto structs.
categories = [
%MyApp.Category{
id: 1,
name: "Electronics",
products: #Ecto.Association.NotLoaded<association :products is not loaded>
},
%MyApp.Category{
id: 2,
name: "Furniture",
products: #Ecto.Association.NotLoaded<association :products is not loaded>
}
]
products = [
%MyApp.Product{
id: 1,
name: "TV",
category_id: 1
},
%MyApp.Product{
id: 2,
name: "Computer",
category_id: 1
},
%MyApp.Product{
id: 3,
name: "Office Desk",
category_id: 2
}
]
And I want to put products that matches category id into categories list
categories = [
%MyApp.Category{
id: 1,
name: "Electronics",
products: [
products = [
%MyApp.Product{
id: 1,
name: "TV",
category_id: 1
},
%MyApp.Product{
id: 2,
name: "Computer",
category_id: 1
}
]
},
%MyApp.Category{
id: 2,
name: "Furniture",
products: [
%MyApp.Product{
id: 3,
name: "Office Desk",
category_id: 2
}
]
}
]
Enum.reduce(products, categories, fn(product, cat) ->
Enum.find(cat, fn c -> c.id == product.category_id end) |> Map.get_and_update!(:products, fn prev -> {prev, product} end)
end)
But no luck.
I got data from Repo.query and building from Repo.load. So I don’t want to do another database query.
How can I do this?