2017-10-07 47 views
0

我是而不是使用EloquentLaravel5 - 使用數據庫驅動程序更改主鍵列的名稱

我的用戶表使用userid作爲主列名(不id),我有UserItem實現可認證接口和我的配置/ auth.php看起來是這樣的:當我重新命名

'providers' => [ 
     'users' => [ 
      'driver' => 'database', 
      'table' => 'user', 
     ], 
    ], 

一切正常以「ID」列,但如果不這樣做,我得到這個錯誤:因爲這個代碼在我看來

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `user` where `id` = 55 limit 1)... 

(它的默認,只檢查是否顯示登錄/註冊或登錄用戶菜單):

<?php if(auth()->guard()->guest()): ?> 

它的這個指令:

@guest 

我在哪裏可以改變它,所以它不會查找id而是userid呢?

+2

只要改變列ID(它應該是反正):/或重新實現['GenericUser'](HTTPS:// github上。com/laravel/framework/blob/bd352a0d2ca93775fce8ef02365b03fc4fb8cbb0/src/Illuminate/Auth/GenericUser.php#L32) –

回答

1

'driver' => 'database'你不像'driver' => 'eloquent'那麼靈活。
我可以告訴你,id被硬編碼爲數據庫驅動程序和GenericUser類的一部分。

如果你真的想要的位置,比你要看看數據庫驅動程序執行用戶身份驗證:
/vendor/laravel/framework/src/Illuminate/Auth/DatabaseUserProvider.php

public function retrieveById($identifier) 
{ 
    $user = $this->conn->table($this->table)->find($identifier); 

    return $this->getGenericUser($user); 
} 

在這裏,我們與數據庫連接並獲取用戶通過它的標識。到目前爲止好,但這是調用find方法,你會發現,這裏:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php

public function find($id, $columns = ['*']) 
{ 
    return $this->where('id', '=', $id)->first($columns); 
} 

你看id是由數據庫驅動程序所使用的任何簡單的查找方法固定字符串。將其更改爲userid將導致您必須將數據庫中的所有主鍵,當然也包括所有使用id的其他方法。

GenericUser也有id作爲硬編碼值來識別用戶,請參閱:
/vendor/laravel/framework/src/Illuminate/Auth/GenericUser.php

public function getAuthIdentifierName() 
{ 
    return 'id'; 
} 

所以,即使你改變所有iduserid比你不能更新,因爲任何東西都被覆蓋。

我的建議是:如果可以,請使用Laravel Eloquent,或將主標識符保留爲id

供參考:我用Laravel 5.5代碼庫

+0

我明白了。謝謝,下次當數據庫模式被設計時,我會記得命名主列'id'。 – toddddos

相關問題