【问题标题】:Model::Save() tries to send and Id to database that doesnt existModel::Save() 尝试将 ID 发送到不存在的数据库
【发布时间】:2020-11-26 18:13:38
【问题描述】:

我正在尝试使用这段代码将数据保存到 postgres 数据库中的表中:

protected $table = 'measurements';

protected $fillable = ['Measurement_Id','Patient_Id', 'Sensor_Id','Measurement_Type'];

public function saveMeasurement($sensor_Id, $patient_Id, $measurement_type){
    $measurement = new Measurement();

    $measurement->Measurement_Id = Str::Uuid();
    $measurement->Patient_Id = $patient_Id;
    $measurement->Sensor_Id = $sensor_Id;
    $measurement->Measurement_Type = $measurement_type;

    try {
        $measurement->save();

        return "Measurement saved";
    }
    catch (Exception $e){
        return $e;
    }

但我收到此错误消息:

SQLSTATE[42703]:未定义列:7 错误:关系“测量”的列“id”不存在

当我查看发送到数据库的请求时,我看到我也在发送和 id:

(“Measurement_Id”、“Patient_Id”、“Sensor_Id”、“Measurement_Type”、“id”、“updated_at”、“created_at”)

我已尝试重新创建模型和迁移似乎都没有帮助。

【问题讨论】:

  • 你在使用 postgres 吗?
  • @sta 是的,它是一个 postgres 数据库
  • 是的,我的主键是 uuid @sta
  • 在你的模型上添加这一行$incrementing = false;

标签: php laravel postgresql


【解决方案1】:

将这两行添加到您的测量模型中。

 protected $primaryKey = 'Measurement_Id'; // or null

 public $incrementing = false;

【讨论】:

    【解决方案2】:

    Laravel 假设您的主键名称是 id
    您可以使用protected $primaryKey = 'Measurement_Id'; 指定 pk 名称 另外,如果您使用的是 uuid,请禁用增量

     public $incrementing = false;
    

    文档https://laravel.com/docs/8.x/eloquent#primary-keys

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 2012-11-10
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多