limanweb/pg-ext

Laravel 扩展,用于与 PostgreSQL 表的本地字段类型协同工作

安装数: 5,102

依赖者: 0

建议者: 0

安全性: 0

星标: 2

关注者: 1

分支: 0

开放问题: 0

类型:package

v1.2.2 2024-05-28 17:52 UTC

This package is auto-updated.

Last update: 2024-09-28 18:42:37 UTC


README

扩展 Laravel 以与 PostgreSQL 表协同工作

提供

  • 为某些原生 PostgreSQL 类型提供额外的类型转换
  • 使用特定的 PostgreSQL 数组类型字段提供额外的多对多关系

已宣布(开发中)

  • 扩展 BluePrint 以操作 PostgreSQL 数组字段和 GIN 索引

安装

运行

composer require "limanweb/pg-ext"

包内容

  • 模型\
    • 关注点\
      • PgTypeCastable - 为模型转换一些 PostgreSQL 原生类型
      • HasArrayRelationships - 为模型提供额外的关系
    • 模型 - 使用 PgTypeCastable & HasArrayRelationships 特性的抽象模型
  • 关系\
    • ArrayRelations - 数组字段关系的基抽象类
    • HasManyInArray - HasManyInArray 关系类
    • BelongsToManyArrays - BelongsToManyArrays 关系类
  • 支持\
    • PgHelper - PostgreSQL 原生类型转换辅助工具

使用扩展的类型转换

在您的模型中使用 Limanweb\PgExt\Models\Concerns\PgTypeCastable 特性以转换一些原生 PostgreSQL 类型

  1. 将特性 Limanweb\PgExt\Models\Concerns\PgTypeCastable 添加到您的模型中
use Illuminate\Database\Eloquent\Model;

class YourModel extends Model 
{
	use Limanweb\PgExt\Models\Concerns\PgTypeCastable;
	
	// Your model implementation
}	

或将模型从 Limanweb\PgExt\Models\Model 继承,以默认使用扩展的类型转换。

use Limanweb\PgExt\Models\Model;

class YourModel extends Model 
{
	// Your model implementation
}
  1. 在 $casts 属性中描述您的表数组字段,使用 'pg_array'
protected $casts = [
	'your_array_field' => 'pg_array',
];

可用的类型转换

  • pg_array - 用于一维数组字段 ("text[]", "varchar[]", "int[]" 等)

现在您可以像操作 PHP 数组一样操作模型的数组属性。

使用扩展的关系

将特性 Limanweb\PgExt\Models\Concerns\HasArrayRelationships 添加到您的模型中

use Illuminate\Database\Eloquent\Model;

class YourModel extends Model 
{
	use Limanweb\PgExt\Models\Concerns\PgTypeCastable;
	use Limanweb\PgExt\Models\Concerns\HasArrayRelationships;
	
	// Your model implementation
}	

或将模型从 Limanweb\PgExt\Models\Model 继承,以默认使用扩展的类型转换和关系。

通过数组字段的多对多关系

例如,您有两个表:posts(帖子)和tags(标签)。每个帖子可以有多个标签,每个标签也可以与多个帖子相关联。您可以将原生 PostgreSQL 类型 'INTEGER[]'(整数数组)的列 'tag_ids' 添加到 'posts' 表中。现在,您可以使用此字段来指定与帖子相关联的标签的 ID。

注意:不要忘记在 'tag_ids' 字段上创建 GIN 索引。

使用 hasManyInArray 和 belongsToManyArrays 关系可以访问相关模型。下面是示例。

hasManyInArray 关系

use Limanweb\PgExt\Models\Model;

class Post extends Model {

	protected $casts = [
		'name' => 'string',
		'tag_ids' => 'pg_array', 	// this is array of integer PostgreSQL field
						// in SQL is "country_is INTEGER[],"
	];

	// Your model implementation

	/**
	 * @return Limanweb\PgExt\Relations\HasManyInArray
	 */
	public function tags() {
		return $this->hasManyInArray(Tag::class, 'tag_ids', 'id');
	}
}	

belongsToManyArrays 关系

use Limanweb\PgExt\Models\Model;

class Tag extends Model {

	protected $casts = [
		'name' => 'string',
	];

	// Your model implementation

	/**
	 * @return Limanweb\PgExt\Relations\BelongsToManyArrays
	 */
	public function posts() {
		return $this->belongsToManyArrays(Post::class, 'tag_ids', 'id');
	}
}