Ecto: How to preload records with selecting another joined columns

前端 未结 1 1951
野的像风
野的像风 2021-02-14 08:04

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

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

# extract definition of s         


        
相关标签:
1条回答
  • 2021-02-14 09:06

    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]
    

    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]]
    
    0 讨论(0)
提交回复
热议问题