簡體   English   中英

Laravel Eloquent模型id作為字符串返回錯誤的值

[英]Laravel Eloquent model id as string return wrong value in

有一個OauthClient模型,$ client-> id在Laravel 5.2中沒有返回正確的值。

“lucadegasperi / oauth2-server-laravel”:“^ 5.1”用於遷移$ table-> string('id',40) - > primary();

但是當在刀片模板中使用$ client-> id時,我會返回“0”。 使用dd($ client)在id屬性中顯示正確的值。

可能有什么不對?

dd()的模型輸出

OauthClient {#254 ▼
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  #perPage: 15
  +incrementing: true
  +timestamps: true
  #attributes: array:7 [▼
    "id" => "wISw4JmlMQCCrMupjojcuDTK3k4hwtkb"
    "secret" => "nnw3CPTzeQSIfT4KpR0d3XzWIKKoghB3"
    "name" => "http://example.com"
    "package" => "free"
    "user_id" => 2
    "created_at" => "2016-07-19 15:36:28"
    "updated_at" => "2016-07-19 15:36:28"
  ]
  #original: array:7 [▶]
  #relations: []
  #hidden: []
  #visible: []
  #appends: []
  #fillable: []
  #guarded: array:1 [▼
    0 => "*"
  ]
  #dates: []
  #dateFormat: null
  #casts: []
  #touches: []
  #observables: []
  #with: []
  #morphClass: null
  +exists: true
  +wasRecentlyCreated: false
}

“show create table oauth_clients”中的表結構

CREATE TABLE `oauth_clients` (
  `id` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `secret` varchar(40) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `package` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `user_id` int(10) unsigned NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `oauth_clients_id_secret_unique` (`id`,`secret`),
  KEY `oauth_clients_user_id_foreign` (`user_id`),
  CONSTRAINT `oauth_clients_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

這是因為默認情況下,除非另有明確說明,否則主鍵將被轉換為int

(int) "wISw4JmlMQCCrMupjojcuDTK3k4hwtkb" == 0

該值仍然以字符串形式存在,但如果使用$model->id ,它將通過Illuminate\\Database\\Eloquent\\Model類中定義的magic __get()方法。

我不打算反對使用id字段作為字符串,但如果你這樣做並且也希望使用$ model-> id獲取字符串值,則必須在模型定義中將其轉換為字符串。 您可以使用受保護的$ casts數組。 只需將以下內容添加到您的OauthClient模型中:

protected $casts = ['id' => 'string'];

這將執行技巧並將id屬性轉換為字符串而不是默認整數。 雖然我會建議不要首先使用id作為字符串。

更新:

還有一個$incrementing屬性,您可以在模型上將其設置為false ,以告訴Laravel您想要非遞增或非數字主鍵。 將它設置在您的模型上,如下所示:

public $incrementing = false;

更新2:

有關此信息現已添加到官方文檔中。 Eloquent docs中查找主鍵部分:

此外,Eloquent假定主鍵是遞增的整數值,這意味着默認情況下主鍵將自動轉換為int。 如果要使用非遞增或非數字主鍵,則必須將模型上的public $ incrementing屬性設置為false。 如果主鍵不是整數,則應將模型上的protected $ keyType屬性設置為string。

設置public $incrementing = false; 為我工作。

http://www.laravel.io/forum/12-14-2015-id-as-string

暫無
暫無

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

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