Ecto:在many_to_many查询中包含join schema字段

时间:2016-11-15 15:49:56

标签: elixir ecto

我与一个明确的join_schema有一个很多关联,它引用了两端的相同模型(有点像经典的追随者(是用户)< - > Followee(是用户)的东西)。

如果我查询用户的关注者我想要包含跟随用户的时间,那么坚持使用该示例。这些数据显然位于连接模式上(让我们的呼叫是订阅)。

如果只想要关注者,我会这样做:

followers = User
|> Repo.get!(user_id)
|> assoc(:followers)
|> Repo.all()

为了让这个工作,我会在用户上定义:

many_to_many(
  :followers,
  MyApp.User,
  join_through: MyApp.Subscription,
  join_keys: [followee_id: :id, follower_id: :id]
)

因此,我们假设created_at模型上有Subscription字段。我该如何查询才能得到它?

1 个答案:

答案 0 :(得分:1)

由于您已拥有Subscription架构,因此您可以定义has_many

schema "users" do
  ...
  has_many :follower_subscriptions, MyApp.Subscription, foreign_key: :followee_id
  has_many :followee_subscriptions, MyApp.Subscription, foreign_key: :follower_id
end

然后使用以下方式获取订阅:

follower_subscriptions = User
|> Repo.get!(user_id)
|> Repo.preload(follower_subscriptions: :follower)
|> Repo.all()

follower_subscriptions将是Subscription的列表,每个列表包含created_atfolloweefollowee_idfollower_id

未经测试的代码;如果有拼写错误,请告诉我。

相关问题