laravel Eloquent 模型返回 0 作为主键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34458985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 12:53:23  来源:igfitidea点击:

Eloquent model returns 0 as primary key

laraveleloquent

提问by Alan

I have this migration:

我有这个迁移:

Schema::create('provincias', function (Blueprint $table) {
    $table->string('codigo', 2);
    $table->string('nombre', 50);
    $table->timestamp('creado');
    $table->primary('codigo');
});

This is my model:

这是我的模型:

class Provincia extends Model
{   
    protected $primaryKey = 'codigo';
    public $timestamps = false;
}

I run the migration and save data like this:

我运行迁移并像这样保存数据:

$provincia = new Provincia;
$provincia->codigo = "BA";
$provincia->nombre = "Buenos Aires";
$provincia->save();

The problem is that when I get all and dump:

问题是,当我得到所有并转储时:

$provincias = Provincia::all();
return $provincias;

The primary key "codigo" is always 0 even when I check the database table and it has the proper value:

即使我检查数据库表并且它具有正确的值,主键“codigo”也始终为 0:

{
    codigo: 0,
    nombre: "Buenos Aires",
    creado: "2015-12-24 21:00:24"
}

回答by lagbox

You can try setting public $incrementing = false;on your model so eloquent doesn't expect your primary key to be an autoincrement primary key.

您可以尝试public $incrementing = false;在您的模型上进行设置,因此 eloquent 不希望您的主键是自动增量主键。

回答by StrongLucky

You can also set the type of primary key:

您还可以设置主键的类型:

protected $keyType = 'string';
public $incrementing = false;

Important note. You should add the second line. $incrementing = false. If you do not this, the key will be 0 after calling save()on your model.

重要的提示。您应该添加第二行。$incrementing = false. 如果你不这样做,调用save()你的模型后,key 将为 0 。