There is some ambiguity in the documentation as to how limit and filter can be applied together. I thought the following seemed logical - there are four user groups, one of which is superadmin ID 1:
$member_groups = ee('Model')->get($member_groups)->all()->filter('group_id', '!=', 1)->limit(1);This throws an error
Exception Caught No such method limit. /ee3.beta/system/ee/EllisLab/ExpressionEngine/Library/Mixin/Manager.php:143
Putting the ‘limit’ condition before the ‘all’ as shown in the docs, but keeping the filter as follows:
$member_groups = ee(‘Model’)->get($member_groups)->limit(1)->all()->filter(‘group_id’, ‘!=’, 1);
results in:
object(EllisLab\ExpressionEngine\Service\Model\Collection)[458] private ‘association’ => null protected ‘elements’ => array (size=0) empty
What I had hoped for was that filter would be applied before the limit condition is applied.
Hi John,
The issue in this case is actually the position of all(). The methods all() and first() will run the query and return its result. As a rule of thumb, they should always be last.
// get the first member group that isn't the super admin
$member_groups = ee('Model')->get('MemberGroup')->filter('group_id', '!=', 1)->limit(1)->all();After running a query with all(), you’ll have a collection object. It’s basically a fancy array of models with some useful methods on it. For example, to turn your member groups into an associative array of group_id => group_title, you could do:
// getDictionary is a collection method
$group_dropdown = $member_groups->getDictionary('group_id', 'group_title');Since you’re using a limit of 1, your query will always have a collection of size 1. This is usually an indicator that you can use first() instead. This does an implicit limit of 1 and returns a single model instance instead of a collection:
$first_non_admin_group = ee('Model')->get('MemberGroup')->filter('group_id', '!=', 1)->first();Keep in mind, that you always want your initial query to be as narrow as possible so you don’t run out of memory. Rarely should you see an all() without a filter(). A filter() after an all() is the filter method on the collection, which is useful for extracting a subset of the models you queried for.
I hope that helps!
Packet Tide owns and develops ExpressionEngine. © Packet Tide, All Rights Reserved.