laragrad/eloquent-model-pg-casts

v1.0.1 2023-12-06 16:05 UTC

This package is auto-updated.

Last update: 2024-09-06 18:04:14 UTC


README

本包提供了一个特质 \Laragrad\Models\Concerns\PgTypeCastable,该特质为 Eloquent\Model 添加了一些 PostgreSQL 特定的字段类型转换。

安装

在控制台运行命令

composer require laragrad/eloquent-model-pg-casts

添加的类型转换

  • pg_array - 用于任何数组字段
  • pg_text_array - 用于 text[] 字段
  • pg_uuid_array - 用于 uuid[] 字段
  • pg_int_array - 用于 int[] 字段
  • pg_numeric_array - 用于 numeric[] 字段

使用方法

例如,表 test_groups 有一个字段 test_ids uuid[],并且你为这个表创建了模型。

添加到模型中

  • 使用特质的声明 \Laragrad\Models\Concerns\PgTypeCastable
  • 为属性 test_ids 添加类型转换 pg_uuid_array
class TestGroup extends Model 
{
    use \Laragrad\Models\Concerns\PgTypeCastable;

    protected $casts = [
    	'test_ids' => 'pg_uuid_array',
    ];
}

代码示例

>>> $m = new App\TestGroup();
>>> $m->title = 'First group';
>>> $m->test_ids = ['00000000-0000-0000-0000-000000000001','00000000-0000-0000-0000-000000000002'];
>>> $m->save();
>>> $m->refersh();
>>> $m
=> App\TestGroup {#3171
     id: 1,
     title: "First group",
     test_ids: "{00000000-0000-0000-0100-000000000001,00000000-0000-0000-0100-000000000002}",
   }
>>> $m->test_ids
=> [
     "00000000-0000-0000-0100-000000000001",
     "00000000-0000-0000-0100-000000000002",
   ]
>>> $m->toArray()
=> [
     "id" => 1,
     "title" => "First group",
     "test_ids" => [
       "00000000-0000-0000-0100-000000000001",
       "00000000-0000-0000-0100-000000000002",
     ],
   ]