Eloquent 模型返回 0 作为主键 [英] Eloquent model returns 0 as primary key

查看:30
本文介绍了Eloquent 模型返回 0 作为主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个迁移:

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

这是我的模型:

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;

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

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

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

推荐答案

您可以尝试在您的模型上设置 public $incrementing = false; 以便 eloquent 不希望您的主键是自动增量主键.

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

这篇关于Eloquent 模型返回 0 作为主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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