2

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

Imran Ali
  • 372
  • 5
  • 16

1 Answers1

0

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();
lewis4u
  • 14,256
  • 18
  • 107
  • 148
  • Actually, I don't want to use Laravel model relationship because of performance issues. Moreover, I want to make use of local scopes. i.e. $users = Users::active()->join('user_subscriptions', 'users.id', '=','user_subscriptions.user_id') ->UserSubscription::type() ->get(); @lewis4u – Imran Ali Jan 15 '17 at 08:52
  • But as far as I know the scopes are based on eloquent. And I would like to know if you could post a link or something of an example with eloquent performance issues. – lewis4u Jan 15 '17 at 09:40