【发布时间】:2020-12-07 22:33:10
【问题描述】:
我有一个在 p.followings 中返回的 Persona 模型列表,我想从该模型列表中提取 followed_id 字段到一个单独的列表中。
p.followings
returns...
[
%Poaster.Personas.Following{
__meta__: #Ecto.Schema.Metadata<:loaded, "followings">,
followed: %Poaster.Personas.Persona{
__meta__: #Ecto.Schema.Metadata<:loaded, "personas">,
background_image_url: nil,
bio: "ASDF",
followings: #Ecto.Association.NotLoaded<association :followings is not loaded>,
id: 42,
inserted_at: ~N[2020-08-14 01:52:17],
name: nil,
profile_image_url: nil,
updated_at: ~N[2020-08-14 16:19:56],
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 1,
username: "test"
},
followed_id: 42,
id: 1,
inserted_at: ~N[2020-08-12 20:35:09],
persona: #Ecto.Association.NotLoaded<association :persona is not loaded>,
persona_id: 1,
updated_at: ~N[2020-08-12 20:35:09]
}
]
我只是想在此处获取followed_id 的列表,这样我就可以进行查询以从我关注的那些角色中获取帖子列表。
我想找回像[42] 这样的东西。
当我执行 Enum.map(ps.followings, fn follow -> follow.followed_id end) 时,这是我期望能够运行的,我回到控制台只是 '*'
当我尝试使用带有 into 选项的推导式进入一个空列表时,这也是我得到的。
persona_ids = []
for p <- p.followings, into: persona_ids, do: p.followed_id
IO.inspect(persona_ids)
[]
但是,当我使用p.followed 运行上述理解时,它会返回一个角色列表:
for p <- p.followings, into: persona_ids, do: p.followed
[
%Poaster.Personas.Persona{
__meta__: #Ecto.Schema.Metadata<:loaded, "personas">,
background_image_url: nil,
bio: "ASDF",
followings: #Ecto.Association.NotLoaded<association :followings is not loaded>,
id: 42,
inserted_at: ~N[2020-08-14 01:52:17],
name: nil,
profile_image_url: nil,
updated_at: ~N[2020-08-14 16:19:56],
user: #Ecto.Association.NotLoaded<association :user is not loaded>,
user_id: 1,
username: "test"
}
]
我需要 ID 列表,而不是角色模型列表,以便我可以进行适当的 Ecto 查询以从我关注的角色中获取帖子。
这里发生了什么?我究竟做错了什么?有没有更好的方法来做我想做的事情?
【问题讨论】:
-
'*'实际上等价于[42],因为 42 是*的代码点,并且当您在 Elixir 中创建一个包含所有字符代码点的整数的列表时,您会打印出 charlist当您尝试打印它时,您应该能够正常使用该列表。尝试在该结果上执行List.first,您会看到它产生 42。 -
stackoverflow.com/questions/30037914/…你可能会在这里找到答案
-
嗯.....这确实回答了一些问题。谢谢,@sbacarob!
-
如果您在帖子中回答此问题,我会将其标记为已接受
-
还要注意,在推导式中使用
into:不会影响之前声明的persona_ids变量,因为所有变量在Elixir 中都是不可变的。
标签: elixir list-comprehension phoenix-framework ecto