How do I get all the users with an active subscription in Commerce 2? I want to be able to filter entries by subscribed users.
2 Answers
I solved this by creating a simple plugin.
use craft\db\Query;
class MyPluginVariable
{
public function allActivelySubscribedUserIds()
{
$subscribedUserIds = (new Query())
->select('userId')
->from(['{{%commerce_subscriptions}}'])
->distinct()
->all();
// Create array of just user IDs
$subscribedUserIds = array_column($subscribedUserIds, 'userId');
return $subscribedUserIds;
}
}
I my case I needed to display all entries authored by users that are currently subscribed. In my template I used the variable like this:
{% set subscribedUserIds = craft.MyPlugin.allActivelySubscribedUserIds %}
{% set entries = craft.entries()
.authorId(subscribedUserIds)
.all()
%}
Not Commerce 2, but in Commerce 3, like this:
{% set userIdsWithSubscriptions = craft.subscriptions.limit(null).all()|group('userId')|keys %}
{% set users = craft.users.id(userIdsWithSubscriptions).all() %}
<ul>
{% for user in users %}
<li>{{ user.username }}</li>
{% endfor %}
</ul>
Via Nathaniel @ Craft Support (thanks!)
-
2FYI: this may need some optimization, depending on the scale of your application, like selection of specific columns (
.select('userId').column()
, instead of.all() | group('userId') | keys
), as loading all Element data + instantiating the models can quickly exhaust memory—we've seen major slowdowns after about 1K elements, and out-of-memory errors at 10K. Commented Mar 16, 2020 at 19:06 -
1Thanks @AugustMiller that's good to add in. I am using a mixture of
.with
and pagination, but I think I may add in the.select
too– iamkeirCommented Mar 18, 2020 at 16:09