2
votes

I wanted to know if its possible to use Laravel's local scope between two or more Models using join or sub query?

For example this is User model with scope active.

class User extends Model
{
    public function scopeActive($query)
    {
      return $query->where('active', 1);
    }
}

Other Model is UserSubscription with scope.

class UserSubscription extends Model
{
    public function scopeType($query, $type)
    {
      return $query->where('type', $type);
    }
}

How to make use of both scopes in single query? Following statement will not work.

$users = Users::active()
        ->join('UserSubscription', 'users.id', '=','UserSubscription.user_id')
        ->UserSubscription::type()
        ->get();

I am using Laravel 5.2. https://laravel.com/docs/5.3/eloquent#local-scopes

1

1 Answers

0
votes

If you made right your model relationships in both model classes you can make a query like this:

$users= User::where('active', 1)->whereHas('user_subscriptions', function ($query) {
    $query->where('type', $type);
})->get();