ecto:如何通过选择另一个联接的列来预加载记录 [英] Ecto: How to preload records with selecting another joined columns

查看:61
本文介绍了ecto:如何通过选择另一个联接的列来预加载记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过选择其他联接的列来预加载记录?

Are there any ways to preload records by selecting another joined columns?

# table structure
# User 1---* Post 1---* PostTag *---1 Tag

# extract definition of scheme
scheme "posts" do
 ...
 has_many :post_tags, PostTag
 has_many :tags, [:post_tags, :tag]
end

下面的伪代码表达了我的目标(但不起作用).

Following pseudo-code expresses my goal(but not work).

query = from post in Post,
  join: user in User, on post.user_id == user.id,
  select: %{
    id: post.id,
    title: post.title,
    user_name: user.name, # <= column at joined table
  },
  preload: [:tags]
Repo.all(query)
#=> ** (Ecto.QueryError) the binding used in `from` must be selected in `select` when using `preload` in query:`

我希望这样的结果.

[
  %{id: 1, title: "AAA", user_name: "John", tags: [%{name: "elixir"},...]},
  %{id: 2, title: "BBB", user_name: "Mike", tags: [%{name: "erlang"},...]},
  ...
]

推荐答案

如错误消息所述,您需要选择在预加载时在from中给定的绑定,否则Ecto没有放置预加载标签的位置.这是一个简单的答案:

As the error message says, you need to select the binding you gave in from when you are preloading, otherwise Ecto has no place to put the preloaded tags. Here is a simple answer:

query = from post in Post,
  join: user in User, on post.user_id == user.id,
  select: {post, user.name},
  preload: [:tags]

通过返回一个元组,您可以在侧面看到完整的帖子和user.name.另一种方法是将帖子和用户都返回为完整结构:

By returning a tuple, you can have the full post and the user.name on the side. Another approach is to return both post and users as full structs:

query = from post in Post,
  join: user in User, on post.user_id == user.id,
  preload: [:tags, user: user]

或者如果您不希望所有字段:

or if you don't want all fields:

query = from post in Post,
  join: user in User, on post.user_id == user.id,
  preload: [:tags, user: user],
  select: [:id, :title, :user_id, user: [:name]]

这篇关于ecto:如何通过选择另一个联接的列来预加载记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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