Laravel 5.6 Eloquent 方法未返回数据

Laravel 5.6 Eloquent method not returning data

在我的Userclass中有如下关系:

/**
 * Roles of a User
 *
 * @return \Illuminate\Database\Eloquent\Relations\hasManyThrough
 */
public function roles()
{
    return $this->hasManyThrough(Role::class, UserRole::class, 'user_id', 'id');
}

我已经根据传入的角色创建了一个 return 布尔值的方法:

/**
 * Is User of a given Role?
 *
 * @return bool
 */
public function hasRole($roleShort = null)
{
    if (!$roleShort) {

        return false;

    }

    $result = $this->roles
        ->where('roles.short', '=', $roleShort)
        ->first();

    return $result ? true : false;
}

Tinker 中,我得到了第一个用户和 return 他的角色,并且按预期工作正常。但是当我将角色短名称传递给 hasRole 方法时,它总是 returns false.

>>> $u = User::find(1);
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
=> App\Models\User {#839
     id: 1,
     uuid: "4e86a284-ae1f-4753-a243-797dc5ce98fc",
     name: "Test User",
     email: "mytest@myapp.com",
     country_id: 11,
     partner_id: null,
     region_id: 1,
     language_id: 1,
     time_zone_id: 387,
     date_format_id: 1,
     time_format_id: 11,
     date_time_format_id: 13,
     activated_at: "2018-04-01 14:00:00",
     deleted_at: null,
     created_at: "2018-04-01 22:53:32",
     updated_at: "2018-04-01 22:53:32",
   }

>>> $u->roles
=> Illuminate\Database\Eloquent\Collection {#820
     all: [
       App\Models\Role {#827
         id: 1,
         partner: 0,
         name: "Admininstrator",
         short: "ADMIN",
         user_id: 1,
       },
     ],
   }

>>> $u->hasRole('ADMIN');
=> false

我错过了什么?我尝试记录 SQL 查询,但出现以下错误:

Log::info($this->roles
    ->where('roles.short', '=', $roleShort)
    ->first()
    ->toSql());

>>> $u->hasRole('ADMIN');
PHP Error:  Call to a member function toSql() on null in /home/vagrant/src/sdme/app/Models/User.php on line 126

您正在查询不正确的属性。您的属性是 short 而不是 roles.short.

此外,您可以使用 exists() 方法获得 boolean 结果。

/**
 * Is User of a given Role?
 *
 * @return bool
 */
public function hasRole($roleShort = null)
{
    if (! $roleShort) {
        return false;
    }

    return $this->roles()->where('short', $roleShort)->exists();
}

您还在 Collection 而非 Query\Builder 实例上调用了 where()toSql()。请注意我的回答中 roles 后的括号 - roles().