我是一个新的灵丹妙药,并寻找正确的方式,如何在埃克托模式的念经关系。
假设我有关系模型:
schema "topic" do
has_many :topic_meta, PhoenixApp.TopicMeta并查询预加载:
topic = from t in query,
left_join: meta in assoc(t, :topic_meta),
preload: [topic_meta: meta]
|> Repo.one获取具有列表字段%PhoenixApp.Topic{...}的映射topic_meta
我希望在一个topic_meta字段中更改值:
changed_meta = %{List.first(topic.topic_meta) | last_read: "newValue"}问题:
如何从我的查询中插入已更改的topic_meta关系文件到topic?让更新字段的新查询看起来是不必要的。
详细更新:
first_meta = List.first(topic.topic_meta) // this is first meta
result = Repo.update!(PhoenixApp.Topic.changeset(first_meta, %{last_read: "newValue"}))
case result do
{:ok, topic_meta} ->
// topic_meta successfully updated, but topic does not contain this model
end发布于 2016-04-13 07:10:39
如果您的changed_meta处于要更新的状态,则应使用Repo.update/2
Repo.update(changed_meta)希望这能帮上忙!
更新
如果希望在不重新加载的情况下看到元素在topic中更新,可以手动替换当前的topic_meta列表。
考虑到您已经准备好了change_meta,您可以这样做:
index = Enum.find_index(topic.topic_meta &(&1.id == changed_meta.id))
list = List.replace_at(topic.topic_meta, index, changed_meta)
topic = %{topic | topic_meta: list}这样,最后一行中的topic将有更新的topic_meta列表,其中包含changed_meta的列表。
发布于 2016-04-12 21:20:41
使用build_assoc assoc/3
changed_meta = Ecto.build_assoc(topic, :topic_meta, last_read: "newValue")
Repo.insert!(comment)https://stackoverflow.com/questions/36582842
复制相似问题