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

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

问题描述

 <?php 

命名空间应用程序;

使用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: :27:44,
updated_at:2016-01-03 22:27:44
}

所以,验证令牌 / 主键变为0。



任何人都可以帮忙吗?

解决方案

这是添加到2015年12月29日的升级文档,所以如果您之前升级,可能会错过。



从该模型检查该列是否应该被转换为整数,字符串等。



默认情况下,对于自动递增表,ID被假定为整数在这种方法中:



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



所以解决方案是:

  class UserVerification extends Model 
{
protected $ primaryKey ='your_key_name'; //或null

public $ incrementing = false;
}


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';
}

And my DB is like this-

but if I do this-

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

I am getting this-

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

So, the verification token/primary key becomes 0.

Can anyone please help?

解决方案

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.

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

So the solution is:

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;
}

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

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