XF 2.0 Get thread watchers (with state)

CMTV

Well-known member
Is there a stable and clean way to get all users that are watching given thread including email subscription?

Something like:
PHP:
$watchers = getWatchers($thread);

I searched for this in xF code and found only this very strange construction:
PHP:
!empty($thread->Watch[$visitor->user_id])

I also found setWatchState($thread, $user, $state) method but there is no getWatchState(...) method...

Another way might be using xf_thread_watch table directly as it contains all data I need (user_id, thread_id, email_subscription)...
 
PHP:
$thread->Watch

This is exactly what you're looking for. $thread->Watch will give you the thread-watch relation for the given thread for all users. Have a look at XF\Entity\Thread, line 1075: The watch-relation points to the entity XF:ThreadWatch, with a TO_MANY relation, meaning what you will get back when you call $thread->Watch is an entity collection, which you can treat exactly like a collection you'd receive when you call fetch() on a finder.
 
Thank you @katsulynx!

The final code that displays all thread watchers (+ email subscription):
PHP:
$watchers = $thread->Watch;
       
foreach ($watchers as $watcher)
{
    echo "User with id: " . $watcher->user_id . ". Email: " . (int)$watcher->email_subscribe . "<br>";
}
 
Back
Top Bottom