Laravel 5.2 - 使用字符串作为 Eloquent Table 的自定义主键变为 0 [英] Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

查看:17
本文介绍了Laravel 5.2 - 使用字符串作为 Eloquent Table 的自定义主键变为 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用电子邮件作为我的表的主键,所以我雄辩的代码是-

I am trying to use email as my table's primary key, so my eloquent code is-

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserVerification extends Model
{
    protected $table = 'user_verification';
    protected $fillable =   [
                                'email',
                                'verification_token'
                            ];
    //$timestamps = false;
    protected $primaryKey = 'verification_token';
}

我的数据库是这样的-

但是如果我这样做-

UserVerification::where('verification_token', $token)->first();

我得到这个-

{
  "email": "sdfsdf@sdfsdf.sdf",
  "verification_token": 0,
  "created_at": "2016-01-03 22:27:44",
  "updated_at": "2016-01-03 22:27:44"
}

因此,验证令牌/主键变为 0.

有人可以帮忙吗?

推荐答案

这是添加到升级中2015 年 12 月 29 日的文档,因此如果您在此之前升级,您可能会错过它.

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

从模型中获取任何属性时,它会检查该列是否应转换为整数、字符串等.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

默认情况下,对于自动递增表,此方法中的 ID 假定为整数:

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

所以解决方案是:

class UserVerification extends Model
{
    // if your key name is not 'id'
    // you can also set this to null if you don't have a primary key
    protected $primaryKey = 'your_key_name';

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';
}

这篇关于Laravel 5.2 - 使用字符串作为 Eloquent Table 的自定义主键变为 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆