Downloads
Stars
Version
Extending the laravel to work with PostgreSQL tables
Run:
composer require "limanweb/pg-ext"
Use trait Limanweb\PgExt\Models\Concerns\PgTypeCastable in your model to cast some native PostgreSQL types
Limanweb\PgExt\Models\Concerns\PgTypeCastable
into your modeluse Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
use Limanweb\PgExt\Models\Concerns\PgTypeCastable;
// Your model implementation
}
or inherite your model from Limanweb\PgExt\Models\Model
to use extended casting by default.
use Limanweb\PgExt\Models\Model;
class YourModel extends Model
{
// Your model implementation
}
protected $casts = [
'your_array_field' => 'pg_array',
];
Available cast types:
Now you can operate with array-attributes of model like with PHP-array.
Add trait Limanweb\PgExt\Models\Concerns\HasArrayRelationships
into your model
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
use Limanweb\PgExt\Models\Concerns\PgTypeCastable;
use Limanweb\PgExt\Models\Concerns\HasArrayRelationships;
// Your model implementation
}
or inherite your model from Limanweb\PgExt\Models\Model
to use extended casting and relationships by default.
For example, you have two tables: posts and tags. Every post can have many tags, and every tag can be associated with many posts. You can add a column 'tag_ids' of native PostgreSQL type 'INTEGER[]' (array of integer) into 'posts' table. Now, you can use this field to specify ID-s of tags associated with post.
Notes: Don't forget to create GIN-index on 'tag_ids' field.
Using the hasManyInArray and the belongsToManyArrays relationships allows you to access related models. See examples below.
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');
}
}
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');
}
}