1- from sqlalchemy import Column , Integer , String , ARRAY , Enum
2- from sqlalchemy .orm import backref , relationship
1+ from sqlalchemy import Column , Integer , String , ARRAY , Enum , ForeignKey
2+ from sqlalchemy .orm import relationship
33from src .database import Base
44from src .models .enums import DayOfWeekEnum
5+ from src .models .friends import Friendship
56
67class User (Base ):
78 """
@@ -30,4 +31,48 @@ class User(Base):
3031 active_streak = Column (Integer , nullable = True )
3132 max_streak = Column (Integer , nullable = True )
3233 workout_goal = Column (ARRAY (Enum (DayOfWeekEnum )), nullable = True )
33- encoded_image = Column (String , nullable = True )
34+ encoded_image = Column (String , nullable = True )
35+
36+ friend_requests_sent = relationship ("Friendship" ,
37+ foreign_keys = "Friendship.user_id" ,
38+ back_populates = "user" )
39+
40+ friend_requests_received = relationship ("Friendship" ,
41+ foreign_keys = "Friendship.friend_id" ,
42+ back_populates = "friend" )
43+
44+ def add_friend (self , friend ):
45+ # Check if friendship already exists
46+ existing = Friendship .query .filter (
47+ (Friendship .user_id == self .id ) &
48+ (Friendship .friend_id == friend .id )
49+ ).first ()
50+
51+ if not existing :
52+ new_friendship = Friendship (user_id = self .id , friend_id = friend .id )
53+ # Add to database session here or return for external handling
54+ return new_friendship
55+
56+ def remove_friend (self , friend ):
57+ friendship = Friendship .query .filter (
58+ (Friendship .user_id == self .id ) &
59+ (Friendship .friend_id == friend .id )
60+ ).first ()
61+
62+ if friendship :
63+ # Delete from database session here or return for external handling
64+ return friendship
65+
66+ def get_friends (self ):
67+ # Get users this user has added as friends
68+ direct_friends_query = Friendship .query .filter_by (user_id = self .id )
69+ direct_friends = [friendship .friend for friendship in direct_friends_query ]
70+
71+ # Get users who have added this user as a friend
72+ reverse_friends_query = Friendship .query .filter_by (friend_id = self .id )
73+ reverse_friends = [friendship .user for friendship in reverse_friends_query ]
74+
75+ # Combine both lists and remove duplicates
76+ all_friends = list (set (direct_friends + reverse_friends ))
77+
78+ return all_friends
0 commit comments