Postgresql EXTO/Elixir/Phoenix-获取没有关联记录的记录
我有以下模式:Postgresql EXTO/Elixir/Phoenix-获取没有关联记录的记录,postgresql,elixir,phoenix-framework,ecto,Postgresql,Elixir,Phoenix Framework,Ecto,我有以下模式: schema "players" do field :email, :string has_many :profiles, MyApp.Profile has_many :worlds, through: [:profiles, :world] end 默认情况下,所有玩家在创建的每个世界中都应该有一个设置。但由于代码中的逻辑错误,一些玩家在某些世界中没有设置 现在我正试图找到那些在某些世界中没有现有设置的玩家,这样
schema "players" do
field :email, :string
has_many :profiles, MyApp.Profile
has_many :worlds, through: [:profiles, :world]
end
默认情况下,所有玩家在创建的每个世界中都应该有一个设置。但由于代码中的逻辑错误,一些玩家在某些世界中没有设置
现在我正试图找到那些在某些世界中没有现有设置的玩家
,这样我就可以使用播种机为他们创建默认设置
我尝试过这样的变通方法:
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语句。它需要大量的数据库工作。
在一些世界
中,有没有办法通过查询获取那些玩家
中没有设置的记录
子查询=
从profile中的profile,
加入:玩家对玩家,
on:player.id==profile.player\u id,
加入:世界中的世界,
打开:world.id==profile.world\u id
质疑=
从“设置”中的设置,
联接:子查询(子查询)中的配置文件,
打开:setting.player\u id==profile.player\u id和
setting.world\u id==profile.world\u id
或者,更简单的是,您可以直接将设置加入player\u id
和world\u id
上的配置文件
后者表明您实际上有一个设计缺陷。设置和配置文件基本上是相同的实体,表示两次。这就是为什么你有矛盾。使用“设置”中的任何字段丰富配置文件,并完全取消设置。是否有返回所需结果的sql查询?我想你可以在玩家和世界上做一个完整的连接,用匹配的档案过滤掉那些记录。老实说,当数据库查找失败时,我会让我的服务返回默认值,而不是将多个(数百?数千?)默认配置文件记录塞进您的配置文件表中。谢谢您的回答。我明白了,有一个设计缺陷。我正在考虑重新设计设置表,并将其与配置文件表关联,而不是与世界和玩家关联。我试过你的例子,我得到了所有现有的设置记录。我试图获取的是在某些世界中没有现有设置记录的玩家。这个问题和我的很相似。我试图用外星碎片将答案转换成长生不老药,但仍然没有运气。也许我做错了。使用outer\u join
或者类似的方法,我无法在没有模式的情况下测试它,但是上面描述的方法是正确的。
schema "settings" do
field :mode, :string
belongs_to :player, MyApp.Player
belongs_to :world, MyApp.World
end
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)