Best-practise question - follow and friends posts in ecto

I tried to reproduce your example, I came up with a user schema like this…

  schema "users" do
    field :name, :string
    field :password, :string, virtual: true
    field :password_digest, :string
    
    many_to_many :friends, User,
      join_through: "friendships",
      join_keys: [friend_a_id: :id, friend_b_id: :id]
    
    many_to_many :reverse_friends, User,
      join_through: "friendships",
      join_keys: [friend_b_id: :id, friend_a_id: :id]
    
    many_to_many :topics, Topic,
      join_through: "follows"
    
    has_many :tweets, Tweet
    
    timestamps()
end

One note is that friendship can be tricky. To get all the friends I am with, I need to query for both direct and reverse friends. Maybe someone can show the way to make this friends association more elegant.

So You can query for direct tweets

q = from t in Tweet, where: t.user_id == ^the_user_id_you_want

Here it is not complete, but You can see the idea

q = from t in Tweet, where: t.user_id in [^friend_1_id, ^friend_2_id…]

I saw here https://hexdocs.pm/ecto/Ecto.Query.html#select/3 that You can use or_where, but I did not yet made the one query you are looking for :slight_smile:

So, in theory (not tested), You shoud be able to do

q = from t in Tweet, where: t.user_id == ^the_user_id_you_want,
or_where: t.user_id in [^friend_1_id, ^friend_2_id…],
or_where: t.topic_id in [^topic_that_user_follows_id, …]

Then, use a distinct: true, an order by date… and whatever You want to do

Please show your schema, so we can compare our way of doing this.