我使用 "table field/column" 作为 varchar 类型而不是整数类型。但为什么要先修剪 0(零)?

I am using "table field/column" as varchar type not integer type. But why trimming first 0(zero)?

在这里, "Phone" 是 "Employee" table 的字段, "Phone" 类型是 string/varchar.

步骤: 1) 保存一条"Employee" 信息 with phone = "01679420786"

迁移:

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->string('phone')->primary();
        $table->string('name');
        $table->string('designation');
        $table->timestamps();
    });
}

型号:

class Employee extends Model
{
    protected $primaryKey = 'phone';
}

2) 获取 Employee 然后 dd()

public function getEmployee()
{
    $employee = Employee::get();
    dd($employee[0]->phone);
    return view('employee.showEmployeeList')->with('employee', $employee);
}

3) 在浏览器中输出:1679420786

使用Laravel框架6.0.3,PHP版本:7.3.2

您正在将模型的主键设置为 phone。在这种情况下,它是一个字符串。默认情况下,Laravel 期望这是一个整数,因此试图将值转换为整数。这是从值的开头删除 0

为了解决这个问题,请将以下 属性 添加到您的模型中。

protected $keyType = 'string';

这告诉 Laravel 主键不是整数而是字符串,因此它会相应地进行转换。

您的模型应该如下所示:

class Employee extends Model
{
    protected $primaryKey = 'phone';

    protected $keyType = 'string';
}