所以我实施了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
答案 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,您将能够轻松完成其他两种方法。 : - )