在 Laravel 上选择 Postgres UUID

Selecting Postgres UUID's on Laravel

我在 Postgres 上有一个自动生成 UUID 的 table,当我在 Laravel 上添加 Customer::all(); 时,我得到一个带有 "cs_id" => "d0402be5-e1ba-4cb2-a80c-5340b406e2c3" 的数组,这很好。当我循环或 select 一条记录只有 cs_id 数据时,它会为当前 table 上的三个记录返回 0,2,5,这是不正确的数据。

编辑:

CREATE TABLE customers
(
  cs_id character varying(255) NOT NULL DEFAULT gen_random_uuid(),
CONSTRAINT cs_customers_pkey PRIMARY KEY (cs_id),
}

在 laravel

$customerData = Customer::where('cs_id','d0402be5-e1ba-4cb2-a80c-5340b406e2c3')->first();

dd($customerData['cs_id']);

使用Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');

获取匹配该 pk 的记录。

我假设你有 use App\Customer;

出于某种原因 Eloquent 搞砸了。

只需添加一个 getter 并在您需要 cs_id

时使用它
public function getGuid()
{
    return $this->attributes['cs_id'];
}

要使用数据库自​​动生成的 uuid,请按如下方式定义您的模型:

class Customer extends Model
{
    // rename the id column (optional)
    protected $primaryKey = 'cs_id';

    // tell Eloquent that your id is not an integer
    protected $keyType = 'string';

    // do NOT set $incrementing to false
}

然后您可以像使用经典 ID 一样使用所有 Eloquent 的方法:

$customerData = Customer::findOrFail('d0402be5-e1ba-4cb2-a80c-5340b406e2c3');