1010use Illuminate \Database \Eloquent \Relations \BelongsToMany ;
1111use Illuminate \Database \Eloquent \Relations \HasMany ;
1212use Illuminate \Database \Eloquent \Relations \HasOne ;
13+ use Illuminate \Support \Facades \DB ;
1314
1415/**
1516 * @template TConversationUser of ConversationUser
2122 * @property ?TMessage $latestMessage
2223 * @property ?TConversationUser $conversationUser Conversation Pivot
2324 */
24- trait HasConversationsTrait
25+ trait ParticipateToConversations
2526{
2627 protected static function bootHasConversationsTrait (): void
2728 {
@@ -71,6 +72,8 @@ public function conversations(): BelongsToMany
7172 }
7273
7374 /**
75+ * Return unread conversations using the `message_reads` table
76+ *
7477 * @return BelongsToMany<TConversation, $this>
7578 */
7679 public function conversationsUnread (): BelongsToMany
@@ -79,13 +82,39 @@ public function conversationsUnread(): BelongsToMany
7982 }
8083
8184 /**
85+ * Return read conversations using the `message_reads` table
86+ *
8287 * @return BelongsToMany<TConversation, $this>
8388 */
8489 public function conversationsRead (): BelongsToMany
8590 {
8691 return $ this ->conversations ()->read ($ this ->id );
8792 }
8893
94+ /**
95+ * Return unread conversations using the pivot column `conversation_user.last_read_message_id`
96+ *
97+ * @return BelongsToMany<TConversation, $this>
98+ */
99+ public function denormalizedConversationsUnread (): BelongsToMany
100+ {
101+ return $ this
102+ ->conversations ()
103+ ->wherePivot ('last_read_message_id ' , '< ' , DB ::raw ('conversations.latest_message_id ' ));
104+ }
105+
106+ /**
107+ * Return read conversations using the pivot column `conversation_user.last_read_message_id`
108+ *
109+ * @return BelongsToMany<TConversation, $this>
110+ */
111+ public function denormalizedConversationsRead (): BelongsToMany
112+ {
113+ return $ this
114+ ->conversations ()
115+ ->wherePivot ('last_read_message_id ' , '>= ' , DB ::raw ('conversations.latest_message_id ' ));
116+ }
117+
89118 /**
90119 * @return BelongsToMany<TConversation, $this>
91120 */
0 commit comments