3

I'm getting all Users from specific UserGroups like this:

$criteria = craft()->elements->getCriteria(ElementType::User);
$criteria->groupId = array(1, 3);
$users = $criteria->find();

But how can I additionally fetch all admin Users?

I tried to add the admin attribute, but this hasn't changed anything:

$criteria->admin = array(false, true);

I assume that's because the ElementCriteriaModel has to match all attributes, but there isn't an admin which has a UserGroup with the ID 1 or 3. But how can I tell the criteria to perform a "OR" fetch?

P.S. I know I could merge two fetched criterias but I want to use a "clean" solution.

4

You won't be able to do that using the ElementCriteriaModel or a single query (unless you use craft ()-> db-> createCommand() or \CDbCriteria to perform a conditional JOIN).

You will either have to 1) do post filtering or 2) get the ids for users in the groups you want and the ids for all admin users (which I would recommend). You can then merge both arrays and use the resulting array to get all users that match the containing ids.

You mentioned that you wanted to do it the clean way and doing a couple of queries using the public Element Query API is definitely the clean way to do it and the fact that you're doing a couple of queries to get the users you want should not feel "unclean" because that is happening in a lot of different places behind the scenes when you use the API instead of raw queries.

For example, when you add the $ criteria->groupId = array(1, 3); to a user query, Craft will hit the db once to get all ids for users in those groups and then hit it again as many times as necessary to do what it needs to do, like perform searches and such.

My point is, using the API means that you might not be able get everything in one go but your plugin won't break if Craft changes any internal APIs.

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.