karimali1337's avatar

Filtering with subscription type

i've 2 type of subscription plans, food & in-role i've made this query to filter if user don't have one of those types and i filtered by it , the user don't show up and its working but the issue is if the user has the 2 types it appear in the 2 filtering and i don't wanna him to appear,any hint to do this

   /**
     * @param string|null $type
     * @return ChildBuilder|Builder|$this
     */
    public function filteredOrAll(
        ?string $type,
    ): ChildBuilder|Builder|static
    {
        if($type) {
            return $this->whereHas('subscriptions.subscriptionItems.sku.product', function ($query) use ($type){
                        $query->where('type','!=',$type);
            });
        }
        return $this;
    }
0 likes
1 reply
LaryAI's avatar
Level 58

To filter out users who have both subscription types, you can modify the query to check if the user has both subscription types and exclude them from the results. Here's an example:

public function filteredOrAll(?string $type): ChildBuilder|Builder|static
{
    if ($type) {
        return $this->where(function ($query) use ($type) {
            $query->whereDoesntHave('subscriptions.subscriptionItems.sku.product', function ($query) use ($type) {
                $query->where('type', $type);
            })->orWhereDoesntHave('subscriptions.subscriptionItems.sku.product', function ($query) use ($type) {
                $query->where('type', '!=', $type);
            });
        });
    }
    return $this;
}

This query uses whereDoesntHave to check if the user doesn't have a subscription of the specified type, and orWhereDoesntHave to check if the user doesn't have a subscription of the other type. This way, if the user has both subscription types, they will be excluded from the results.

Note that this assumes that there are only two subscription types. If there are more, you'll need to modify the query accordingly.

Please or to participate in this conversation.