【问题标题】:laravel eloquent string field for Primary Key goes data error主键的 laravel 雄辩的字符串字段出现数据错误
【发布时间】:2019-10-29 18:50:51
【问题描述】:

我想这太简单了,但是会出现查询结果错误。

我制作了 Country 表,模型。 我只希望它只查询。

唯一不常见的一点是我没有使用“id”字段作为主字段。

我使用 'cc' 字段作为 primary 。

就是这样。但它会响应数据错误。

在迁移文件中

Schema::create('countries', function (Blueprint $table) {
  $table->string('cc')->index()->unique();
  $table->string('name_eng');
  $table->primary('cc');
});

在控制器中

function run() {
  $countries = Country::OrderBy('cc', 'asc')->take(3)->get();
  $data['countries'] = $countries;
  return response()->json( $data, 200);
}

在国家模式中

class Country extends Model
{
    protected $table='countries';
    protected $primaryKey = 'cc';
    public $timestamps = false;
  protected $fillable = ['cc', 'name_eng'];
} 

结果

{
  "countries": [
    {
      "cc": 0, --> it should be 'ad' 
      "name_eng": "Andorra",
    },
    {
      "cc": 0, --> it should be 'ae' 
      "name_eng": "United Arab Emirates",
    },
    {
      "cc": 0, --> it should be 'af' 
      "name_eng": "Afghanistan",
    }
  ]
}

在备份sql中

INSERT INTO `countries` (`cc`, `name_eng`)
VALUES
    ('ad', 'Andorra'),
    ('ae', 'United Arab Emirates'),
    ('af', 'Afghanistan');

为什么我会丢失 'cc' 字段值?

我不明白错误来自哪里。

有人可以帮助我吗?

【问题讨论】:

标签: laravel eloquent orm


【解决方案1】:

在你的模型中写public $incrementing = false

所以模型会明白你的主键是字符串

【讨论】:

  • 谢谢。回复。我在 Laravel 6 上得到了另一个解决方案。在 Model 中,我补充道。受保护的 $keyType = 'string';
猜你喜欢
  • 2022-01-24
  • 1970-01-01
  • 2019-10-01
  • 1970-01-01
  • 2017-05-16
  • 2017-08-04
  • 2018-01-03
  • 1970-01-01
  • 2021-10-02
相关资源
最近更新 更多