• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

XF 2.0 Get thread watchers (with state)

#1
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)...
 

katsulynx

Well-known member
#2
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.
 
#3
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>";
}