【问题标题】:Illuminate\Database\QueryException in Laravel 6.0 but not in 5.8Laravel 6.0 中的 Illuminate\Database\QueryException 但在 5.8 中没有
【发布时间】:2020-02-06 10:32:06
【问题描述】:

我在使用 Laravel 6.0 时遇到问题。相同的源代码在 Laravel 5.8 上运行正常。错误如下:

照亮\数据库\查询异常 SQLSTATE[22018]:[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]将 nvarchar 值“XXXX”转换为数据类型 int 时转换失败。 (SQL: select * from [business_units] where [business_units].[code] in (0, 0, 0, 0))

尝试使用包含相同源代码的 5.8 和 6.0 创建 laravel 项目,但结果相同,在 5.8 中运行良好,但在 6.0 中运行不佳。可能 Eloquent 出了点问题。

这里是迁移:

Schema::create('cost_centers', function (Blueprint $table) {
            $table->string('code', 6)->primary();
            $table->string('descr', 50);
            $table->string('business_unit_code', 6)->index();
            $table->foreign('business_unit_code')->references('code')->on('business_units');
            $table->timestamps();
        });

我的模型脚本是:

class CostCenter extends Model
{
    protected $primaryKey = 'code';
    protected $fillable = ['code', 'descr', 'business_unit_code'];

    public $incrementing = false;

    public function businessUnit()
    {
        return $this->belongsTo(BusinessUnit::class);
    }
}

这是在打开表单后,表中的列引用了主键为字符串的另一列。有没有人遇到过这个问题,你的解决方法是什么?

【问题讨论】:

    标签: laravel-6


    【解决方案1】:

    在表模型“business_units”中,我将声明从 这在使用字符串作为主键时是必要的。

    public $incrementing = false;
    

    protected $keyType = 'string';
    

    正如 Laracast 的 Sinnbeck 向我指出的那样,Laravel 升级指南中对此进行了指定,但不知何故错过了它。 https://laravel.com/docs/6.x/upgrade#eloquent-primary-key-type

    【讨论】:

      猜你喜欢
      • 2020-01-20
      • 2019-05-21
      • 1970-01-01
      • 2022-06-15
      • 2020-09-30
      • 1970-01-01
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多