2

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
  • Is this in the CMS or on the front end?
    – Jason Mayo
    Commented Oct 8, 2018 at 10:24
  • @JasonMayo front end. Commented Oct 8, 2018 at 15:02

2 Answers 2

1

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()
%}
1

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!)

2
  • 2
    FYI: 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
  • 1
    Thanks @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
    – iamkeir
    Commented Mar 18, 2020 at 16:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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