Laravel 5.7 基本上根据一些可能的匹配检查与 auth 用户的相关性的访问器

Laravel 5.7 accessor that essentially checks the relativity to the auth user based on a few possible matches

我的模型有一些范围用于 relativeTonotRelativeTo:

public function scopeRelativeTo($query, User $user)
{
    $teamIDs = $user->teams->pluck('id');

    $query->where('assigned_user_id', $user->id)
        ->orWhere('reported_by', $user->id)
        ->orWhereIn('assigned_team_id', $teamIDs);
}


public function scopeNotRelativeTo($query, User $user)
{
    $teamIDs = $user->teams->pluck('id');

    $query->where('assigned_user_id', '!=', $user->id)
        ->orWhere('reported_by', '!=', $user->id)
        ->orWhereNotIn('assigned_team_id', $teamIDs);
}

这些有助于基于可能的匹配项构建查询,这些匹配项基本上归结为用户是否与对象具有相关性。这些非常适合查询,但我也在尝试在模型上创建一个访问器,它将 return 一个布尔值,这样每个对象都会动态地知道它与经过身份验证的用户的相关性。好主意,但不知道从哪里开始。

public function getRelativityAttribute($value)
{
    $user = User::find(auth('api')->user()->id);
}

对于经过身份验证的用户,并且知道我也可以访问实际的 class:$this,我如何根据范围和 [=23 中的相同检查来检查相关性=] 一个布尔值?

试试这个:

public function getRelativityAttribute($value)
{
    $user = auth('api')->user();
    if (!$user) {
        return false;
    }

    $userId = $user->getKey();
    return $this->assigned_user_id == $userId || $this->reported_by == $userId
           || $user->teams()->where('id', $this->assigned_team_id)->exists();
}