XF 2.2 Best practices in using XF::finder

stromb0li

Active member
This is a bit of a generic ask, but my add-on stores associated records to a user by user_id. When surfacing up information, is it proper to use $finder = \XF::finder('XF:User'); $user = $finder->where('user_id', 1)->fetchOne(); within a foreach loop to get the associated user's information?

If each finder for each user translates to a select * from xf_user table, that seems like a really expensive design / will hammer the database?

Thank you!
 
You could just do your foreach loop to set the user ids to an array then use getUsersByIdsOrdered.

Here's a quick example I believe should work:

PHP:
$ids = [];
foreach ($userIds as $userId)
{
    $ids[] = $userId;
}

$userRepo = \XF::app()->repository('XF:User');
$userList = $userRepo->getUsersByIdsOrdered($ids);
 
If your add-on is retrieving your records using the entity system, you can set up a user relation and eager-load it. Then the corresponding user entity would be available on $yourEntity->User.

Otherwise you can just fetch the users all at once:
PHP:
$users = \XF::em()->findByIds('XF:User', $userIds);
$someUser = $users[$someUserId];
 
Top Bottom