【发布时间】:2021-03-08 19:22:28
【问题描述】:
我有这些架构:
schema "players" do
field :email, :string
has_many :profiles, MyApp.Profile
has_many :worlds, through: [:profiles, :world]
end
schema "worlds" do
field :name, :string
has_many :profiles, MyApp.Profile
has_many :players, through: [:profiles, :player]
end
schema "settings" do
field :mode, :string
belongs_to :player, MyApp.Player
belongs_to :world, MyApp.World
end
默认情况下,所有玩家都应该在他们创建的每个世界中都有一个设置。但是由于我们代码中的逻辑错误,一些玩家在某些世界中没有设置。
现在我正试图找到那些在某些世界中没有现有settings 记录的players,以便我可以使用播种机为他们创建默认设置。
我尝试过这样的解决方法:
query = from profile in Profile
query
|> Repo.all()
|> Enum.each(fn profile ->
case get_settings(profile.player_id, profile.world_id) do
nil ->
create_settings(profile.player_id, profile.world_id)
_ ->
:ok
end
end)
它有效,但我想避免使用 case 语句。它花费了大量的数据库工作。
有什么方法可以使用查询在某些worlds 中获取那些没有settings 记录的players?
【问题讨论】:
-
你有返回你需要的结果的sql查询吗?我想您可以对玩家和世界进行完全连接,并过滤掉具有匹配配置文件的那些记录。老实说,当数据库查找失败时,我只会让我的服务返回默认值,而不是将多个(数百?数千?)默认配置文件记录塞进您的配置文件表中。
标签: postgresql elixir phoenix-framework ecto