Users can block each other. One user can block many (other) users, and one user can be blocked by many (other) users.
In User
model I have these many-to-many relationships:
/**
* Get the users that are blocked by $this user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function blockedUsers()
{
return $this->belongsToMany(User::class, 'ignore_lists', 'user_id', 'blocked_user_id');
}
/**
* Get the users that blocked $this user.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function blockedByUsers()
{
return $this->belongsToMany(User::class, 'ignore_lists', 'blocked_user_id', 'user_id');
}
(ignore_lists
is the pivot table and it has id
, user_id
, 'blocked_user_id'
columns)
I want to create the following Query Scopes:
1) To include users that are blocked by the specified user ($id
):
/**
* Scope a query to only include users that are blocked by the specified user.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param $id
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeAreBlockedBy($query, $id)
{
// How to do this? :)
}
Example of usage: User::areBlockedBy(auth()->id())->where('verified', 1)->get();
2) To include users that are not blocked by the specified user ($id
):
/**
* Scope a query to only include users that are not blocked by the specified user.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param $id
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeAreNotBlockedBy($query, $id)
{
// How to do this? :)
}
Example of usage: User::areNotBlockedBy(auth()->id())->where('verified', 1)->get();
3) To include users that blocked the specified user ($id
):
/**
* Scope a query to only include users that blocked the specified user.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param $id
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhoBlocked($query, $id)
{
// How to do this? :)
}
Example of usage: User::whoBlocked(auth()->id())->where('verified', 1)->get();
4) To include users that did not block the specified user ($id
):
/**
* Scope a query to only include users that did not block the specified user.
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @param $id
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhoDidNotBlock($query, $id)
{
// How to do this? :)
}
Example of usage: User::whoDidNotBlock(auth()->id())->where('verified', 1)->get();
How would you do this? I didn't find anything in the Laravel docs about this (maybe I missed it). (I'm using Laravel 6.x)
I'm not sure, but I think this could be done in two ways: Using Left Join or using raw queries in whereIn... I may be wrong, but I think the "left join" solution would be better as far as performance is concerned, right? (not sure about this, maybe I'm totally wrong).