Reputation: 777
TLTR:
How to get a Collection of from one model (Users) using scope method from another (UserSubscriber)? Models are in one-to-one relation.
More about:
I have two model related one-to-one:
Second model is only for some users that has extended, specific role (subscribers in this case)
User model:
class User extends \Sentinel\Models\User
{
public function subscriber()
{
return $this->hasOne('App\Models\UserSubscriber', 'user_id');
}
}
UserExtended model:
class UserSubscriber extends Model
{
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function scopeLangSubscribers($query, $langCode)
{
$query->where('languages_subscribed', 'LIKE', '%' . $langCode . '%');
}
}
The goal is:
Get a Collection of Users using scope from UserSubscriber.
(Without rewriting this scope method to User model.)
Where I stuck:
$users = User::with(['subscriber' => function ($query) use ($lang) {
$query->langSubscribers($lang);
}])->get();
This returns me collection of all users with 'subscriber' set as null for some of them.
I've tried to filter them, but:
It is probably not the best solution, because it iterates on entire big collection of users after retrieving all of them from DB
$users = $users->filter(function($item) {
return $item->subscriber != null;
});
'subscriber' is not a column, so I can't do:
->whereNotNull('subscriber')
How can I accomplish this?
Edit:
Alternatively, maybe there is a way to convert one collection (of subscribers) to another (users) afterretrieving this first, which can be done very aesy and clean:
$usersSubscribers = UserSubscriber::langSubscribers($lang)->get();
Upvotes: 3
Views: 15408
Reputation: 5124
Use whereHas
instead.
$users = User::with('subscriber')->whereHas('subscriber', function ($query) use ($lang) {
$query->langSubscribers($lang);
})->get();
Upvotes: 5