ecto删除预加载 [英] Ecto remove preload

查看:60
本文介绍了ecto删除预加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以做相反的预加载吗?

 %Post {
评论:[]
}

个帖子= Repo.all(Post)|> Repo.unload(:comments)

%Post {
评论:#Ecto.Association.NotLoaded< association:评论未加载> ;,
}


解决方案

Ecto.Association.NotLoaded 很老简单的结构,因此您自己可以相对容易地实现 unpreload

  defmodule Unpreloader做
def忘记(结构,字段,基数\\:one)做
%{struct |
字段=> %Ecto.Association.NotLoaded {
__field__:字段,
__owner__:struct .__ struct__,
__cardinality__:基数
}
}
结尾
end

以后使用它:



< pre class = lang-rb prettyprint-override> Unpreloader.forget(%Post {....},:comments)


Is there any way to do the inverse to preload?

%Post{
  comments: []
}

posts = Repo.all(Post) |> Repo.unload(:comments)

%Post{
  comments: #Ecto.Association.NotLoaded<association :comments is not loaded>,
}

解决方案

Ecto.Association.NotLoaded is a plain old simple struct, so you might relatively easy implement this unpreload youself:

defmodule Unpreloader do
  def forget(struct, field, cardinality \\ :one) do
    %{struct | 
      field => %Ecto.Association.NotLoaded{
        __field__: field,
        __owner__: struct.__struct__,
        __cardinality__: cardinality
      }
    }
  end
end

And use it later as:

Unpreloader.forget(%Post{....}, :comments)

这篇关于ecto删除预加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆