我正在尝试使用电子邮件作为我表的主键,所以我雄辩的代码是-
<?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';
}
我的数据库是这样的-
https://i.stack.imgur.com/J1jil.png
但如果我这样做——
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。
有人可以帮忙吗?
这是 added to the upgrade documentation on Dec 29, 2015,所以如果您在此之前升级,您可能会错过它。
从模型中获取任何属性时,它会检查该列是否应转换为整数、字符串等。
默认情况下,对于自动递增表,ID 在此方法中假定为整数:
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';
}
在模型上将 $incrementing
设置为 false
public $incrementing = false;
这将阻止它认为它是一个自动增量字段。
Laravel Docs - Eloquent - Defining Models
您需要在模型上设置两个属性。第一个 $primaryKey
告诉模型期望主键在哪一列。第二个 $incrementing
所以它知道主键不是线性自动递增值。
class MyModel extends Model
{
protected $primaryKey = 'my_column';
public $incrementing = false;
}
有关详细信息,请参阅 documentation on Eloquent 中的 Primary Keys
部分。
public $incrementing
才能匹配父类。
我正在使用 Postman 来测试我的 Laravel API。
我收到一个错误,指出
“SQLSTATE[42S22]: Column not found: 1054 Unknown column”,因为 Laravel 试图自动创建两列“created_at”和“updated_at”。
我必须在我的模型中输入 public $timestamps = false;
。然后,我再次使用 Postman 进行测试,发现在我的数据库中创建了一个 "id" = 0
变量。
我最后不得不添加 public $incrementing false;
来修复我的 API。
继续使用身份证
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserVerification extends Model
{
protected $table = 'user_verification';
protected $fillable = [
'id',
'email',
'verification_token'
];
//$timestamps = false;
protected $primaryKey = 'verification_token';
}
并收到电子邮件:
$usr = User::find($id);
$token = $usr->verification_token;
$email = UserVerification::find($token);
$incrementing
字段是公共的而不是受保护的是否有原因?$incrementing
公开而$primaryKey
受保护?这很随意。我猜$incrementing
在早期版本的 Eloquent 中没有 getter 或 setter 方法(现在有),他们只是不想在添加它们后进行重大更改chunk
迭代此类表,您可能会遇到以下错误:SQLSTATE[42S22]: Column not found: 1054 Unknown column 'example.' in 'order clause'
。在这种情况下,您需要显式定义orderBy
语句,Eloquent 会尝试使用主键将其附加到您的查询中。