3

I know how to find user by username and email. The problem comes when I need to query users based on a custom field.

Here is my scenario. I have about 2,000 users (part of a user group 'Affiliates') that I have created in our system. They have many custom fields including affiliateId and studentCount. I need to be able to execute two separate queries.

  1. Find a single user by his/her affiliateId (int).

  2. Query all users within the Affiliate group, order by studentCount asc and return the top record. (I need a user that has the fewest number of students).

I have searched docs and tried numerous combinations to query users. Any help at this point greatly appreciated. Is search the best way? If so, how do you order the search result?

3

Find a single user by his/her affiliateId (int).

$criteria = craft()->elements->getCriteria(ElementType::User);
$criteria->affiliateId = 1;
$users = $criteria->find();

Query all users within the Affiliate group, order by studentCount asc and return the top record. (I need a user that has the fewest number of students).

$criteria = craft()->elements->getCriteria(ElementType::User);
$criteria->affiliateGroup = 'myGroup';
$criteria->order = 'studentCount ASC';
$criteria->limit = 1;
$users = $criteria->find();
  • Re the first code snippet of 3 lines provided above, I am getting Fatal error: Call to a member function find() on a non-object in /var/www/vhosts/.../controllers/MyController.php on line 115. I have verified that affiliateId is in fact a custom field attached to the user record. – David Aaron McInnis Sep 28 '15 at 19:52
  • Sorry, hadn't had coffee yet. Edited post. – Brad Bell Sep 28 '15 at 19:54
  • With one small modification $criteria->groupId = 2; – David Aaron McInnis Sep 29 '15 at 3:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.