在Laravel

时间:2017-04-24 07:16:26

标签: postgresql laravel uuid

我在Postgres上有一个自动生成UUID的表,当我在Laravel上{d} {d} {我获得一个Customer::all();的数组时,这很好。当我循环或选择一个只有cs_id数据的记录时,它会返回当前表中三个不正确数据的记录的0,2,5。

编辑:

"cs_id" => "d0402be5-e1ba-4cb2-a80c-5340b406e2c3"

在laravel上

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

3 个答案:

答案 0 :(得分:2)

出于某种原因,Eloquent在那里搞砸了。

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

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

答案 1 :(得分:1)

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

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');

答案 2 :(得分:0)

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

获取与pk匹配的记录。

我假设你拥有use App\Customer;