簡體   English   中英

Laravel 5.6雄辯的方法不返回數據

[英]Laravel 5.6 Eloquent method not returning data

在我的User類中,我具有以下關系:

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

我創建了一個方法,用於根據傳入的角色返回布爾值:

/**
 * 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我得到了第一個用戶並返回他的角色,並且按預期工作正常。 但是,當我將角色短名稱傳遞給hasRole方法時,它總是返回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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM