Ecto查询自引用关联

时间:2016-11-08 02:38:52

标签: join elixir phoenix-framework ecto

所以我实施了User自引用关联,作为user跟随另一个user ...典型关注者/关注模型的方式。我对如何为下面的每个函数实现正确的查询表达式感到困惑。我理解为每个函数做的假设,但我不知道如何实现它们。

defmodule App.User do  

  schema "users" do
    #...
    has_many :followers, App.Follower, foreign_key: :followed_id
    has_many :following, through: [:followers, :follower]
  end

  #...  

  @doc """
  Return true if `user` is following `user2`
  """
  def following?(user, user2) do
  end

  @doc """
  Return true if `user` is followed by `user2`
  """
  def followed_by?(user, user2) do
  end

  @doc """
  `user` follows `user2` 
  """
  def follow(user, user2) do
  end

  @doc """
  `user` unfollows `user2` 
  """
  def unfollow(user, user2) do
  end

end

Follower架构:

schema "followers" do
  belongs_to :followed, User
  belongs_to :follower, User

  timestamps()
end

2 个答案:

答案 0 :(得分:0)

我也是Elixir的新手,但我将来可能还需要这个,所以我看看这个。我会试试;

def following?(user, user2) do
  user = Repo.get(User, user) |> Repo.preload(:followers)
  followers = hd(user.followers)
  Enum.any?(followers, fn e -> e == user2 end)
end

我不确定这是否有帮助,但我会选择这样的东西。我现在也无法测试它。希望它有所帮助。

答案 1 :(得分:0)

乍一看,你的架构对我来说很好看。我会尝试这样的事情:

def follow(user, user2) do
  Repo.insert! %Follower{follower: user2, followed: user}
end

def following?(user, user2) do
  !! Repo.get_by(Follower, [follower: user2, followed: user]) # !! so that it returns true or false. You can also write xy != nil.
end

查看Ecto.Repo,您将能够轻松完成其他两种方法。 : - )