staudenmeir/eloquent-json-relations
Composer 安装命令:
composer require staudenmeir/eloquent-json-relations
包简介
Laravel Eloquent relationships with JSON keys
README 文档
README
This Laravel Eloquent extension adds support for JSON foreign keys to BelongsTo, HasOne, HasMany, HasOneThrough
, HasManyThrough, MorphTo, MorphOne and MorphMany relationships.
It also provides many-to-many and has-many-through relationships with JSON arrays.
Compatibility
- MySQL 5.7+
- MariaDB 10.2+
- PostgreSQL 9.3+
- SQLite 3.38+
- SQL Server 2016+
Installation
composer require "staudenmeir/eloquent-json-relations:^1.1"
Use this command if you are in PowerShell on Windows (e.g. in VS Code):
composer require "staudenmeir/eloquent-json-relations:^^^^1.1"
Versions
| Laravel | Package |
|---|---|
| 13.x | 1.15 |
| 12.x | 1.14 |
| 11.x | 1.11 |
| 10.x | 1.8 |
| 9.x | 1.7 |
| 8.x | 1.6 |
| 7.x | 1.5 |
| 6.x | 1.4 |
| 5.8 | 1.3 |
| 5.5–5.7 | 1.2 |
Usage
- One-To-Many Relationships
- Many-To-Many Relationships
- Has-Many-Through Relationships
- Deep Relationship Concatenation
One-To-Many Relationships
In this example, User has a BelongsTo relationship with Locale. There is no dedicated column, but the foreign
key (locale_id) is stored as a property in a JSON field (users.options):
class User extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; protected $casts = [ 'options' => 'json', ]; public function locale() { return $this->belongsTo(Locale::class, 'options->locale_id'); } } class Locale extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; public function users() { return $this->hasMany(User::class, 'options->locale_id'); } }
Remember to use the HasJsonRelationships trait in both the parent and the related model.
Referential Integrity
On MySQL, MariaDB, and SQL Server you can still ensure referential integrity with foreign keys on generated/computed columns.
Laravel migrations support this feature on MySQL/MariaDB:
Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->json('options'); $locale_id = DB::connection()->getQueryGrammar()->wrap('options->locale_id'); $table->unsignedBigInteger('locale_id')->storedAs($locale_id); $table->foreign('locale_id')->references('id')->on('locales'); });
Laravel migrations also support this feature on SQL Server:
Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->json('options'); $locale_id = DB::connection()->getQueryGrammar()->wrap('options->locale_id'); $locale_id = 'CAST('.$locale_id.' AS INT)'; $table->computed('locale_id', $locale_id)->persisted(); $table->foreign('locale_id')->references('id')->on('locales'); });
Many-To-Many Relationships
The package also introduces two new relationship types: BelongsToJson and HasManyJson
Use them to implement many-to-many relationships with JSON arrays.
In this example, User has a BelongsToMany relationship with Role. There is no pivot table, but the foreign keys
are stored as an array in a JSON field (users.options):
Array of IDs
By default, the relationship stores pivot records as an array of IDs:
class User extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; protected $casts = [ 'options' => 'json', ]; public function roles(): \Staudenmeir\EloquentJsonRelations\Relations\BelongsToJson { return $this->belongsToJson(Role::class, 'options->role_ids'); } } class Role extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; public function users(): \Staudenmeir\EloquentJsonRelations\Relations\HasManyJson { return $this->hasManyJson(User::class, 'options->role_ids'); } }
On the side of the BelongsToJson relationship, you can use attach(), detach(), sync() and toggle():
$user = new User; $user->roles()->attach([1, 2])->save(); // Now: [1, 2] $user->roles()->detach([2])->save(); // Now: [1] $user->roles()->sync([1, 3])->save(); // Now: [1, 3] $user->roles()->toggle([2, 3])->save(); // Now: [1, 2]
Array of Objects
You can also store pivot records as objects with additional attributes:
class User extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; protected $casts = [ 'options' => 'json', ]; public function roles(): \Staudenmeir\EloquentJsonRelations\Relations\BelongsToJson { return $this->belongsToJson(Role::class, 'options->roles[]->role_id'); } } class Role extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; public function users(): \Staudenmeir\EloquentJsonRelations\Relations\HasManyJson { return $this->hasManyJson(User::class, 'options->roles[]->role_id'); } }
Here, options->roles is the path to the JSON array. role_id is the name of the foreign key property inside the
record object:
$user = new User; $user->roles()->attach([1 => ['active' => true], 2 => ['active' => false]])->save(); // Now: [{"role_id":1,"active":true},{"role_id":2,"active":false}] $user->roles()->detach([2])->save(); // Now: [{"role_id":1,"active":true}] $user->roles()->sync([1 => ['active' => false], 3 => ['active' => true]])->save(); // Now: [{"role_id":1,"active":false},{"role_id":3,"active":true}] $user->roles()->toggle([2 => ['active' => true], 3])->save(); // Now: [{"role_id":1,"active":false},{"role_id":2,"active":true}]
Limitations: On SQLite and SQL Server, these relationships only work partially.
HasOneJson
Define a HasOneJson relationship if you only want to retrieve a single related instance:
class Role extends Model { use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; public function latestUser(): \Staudenmeir\EloquentJsonRelations\Relations\HasOneJson { return $this->hasOneJson(User::class, 'options->roles[]->role_id') ->latest(); } }
Composite Keys
If multiple columns need to match, you can define a composite key.
Pass an array of keys that starts with JSON key:
class Employee extends Model { public function tasks(): \Staudenmeir\EloquentJsonRelations\Relations\BelongsToJson { return $this->belongsToJson( Task::class, ['options->work_stream_ids', 'team_id'], ['work_stream_id', 'team_id'] ); } } class Task extends Model { public function employees(): \Staudenmeir\EloquentJsonRelations\Relations\HasManyJson { return $this->hasManyJson( Employee::class, ['options->work_stream_ids', 'team_id'], ['work_stream_id', 'team_id'] ); } }
Query Performance
MySQL
On MySQL 8.0.17+, you can improve the query performance with multi-valued indexes.
Use this migration when the array is the column itself (e.g. users.role_ids):
Schema::create('users', function (Blueprint $table) { // ... // Array of IDs $table->rawIndex('(cast(`role_ids` as unsigned array))', 'users_role_ids_index'); // Array of objects $table->rawIndex('(cast(`roles`->\'$[*]."role_id"\' as unsigned array))', 'users_roles_index'); });
Use this migration when the array is nested inside an object (e.g. users.options->role_ids):
Schema::create('users', function (Blueprint $table) { // ... // Array of IDs $table->rawIndex('(cast(`options`->\'$."role_ids"\' as unsigned array))', 'users_role_ids_index'); // Array of objects $table->rawIndex('(cast(`options`->\'$."roles"[*]."role_id"\' as unsigned array))', 'users_roles_index'); });
MySQL is quite picky about the syntax so I recommend that you check once
with EXPLAIN that the executed relationship queries
actually use the index.
PostgreSQL
On PostgreSQL, you can improve the query performance with jsonb columns
and GIN indexes.
Use this migration when the array of IDs/objects is the column itself (e.g. users.role_ids):
Schema::create('users', function (Blueprint $table) { $table->id(); $table->jsonb('role_ids'); $table->index('role_ids')->algorithm('gin'); });
Use this migration when the array is nested inside an object (e.g. users.options->role_ids):
Schema::create('users', function (Blueprint $table) { $table->id(); $table->jsonb('options'); $table->rawIndex('("options"->\'role_ids\')', 'users_options_index')->algorithm('gin'); });
Has-Many-Through Relationships
Similar to Laravel's HasManyThrough, you can
define HasManyThroughJson relationships when the JSON column is in the intermediate table (Laravel 9+). This
requires staudenmeir/eloquent-has-many-deep.
Consider a relationship between Role and Project through User:
Role → has many JSON → User → has many Project
Install the additional package, add the
HasRelationships trait to the parent (first) model and pass the JSON column as a JsonKey object:
class Role extends Model { use \Staudenmeir\EloquentHasManyDeep\HasRelationships; public function projects() { return $this->hasManyThroughJson( Project::class, User::class, new \Staudenmeir\EloquentJsonRelations\JsonKey('options->role_ids') ); } }
The reverse relationship would look like this:
class Project extends Model { use \Staudenmeir\EloquentHasManyDeep\HasRelationships; public function roles() { return $this->hasManyThroughJson( Role::class, User::class, 'id', 'id', 'user_id', new JsonKey('options->role_ids') ); } }
Deep Relationship Concatenation
You can include JSON relationships into deep relationships by concatenating them with other relationships using staudenmeir/eloquent-has-many-deep (Laravel 9+).
Consider a relationship between User and Permission through Role:
User → belongs to JSON → Role → has many → Permission
Install the additional package, add the
HasRelationships trait to the parent (first) model
and define a
deep relationship:
class User extends Model { use \Staudenmeir\EloquentHasManyDeep\HasRelationships; use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships; public function permissions(): \Staudenmeir\EloquentHasManyDeep\HasManyDeep { return $this->hasManyDeepFromRelations( $this->roles(), (new Role)->permissions() ); } public function roles(): \Staudenmeir\EloquentJsonRelations\Relations\BelongsToJson { return $this->belongsToJson(Role::class, 'options->role_ids'); } } class Role extends Model { public function permissions() { return $this->hasMany(Permission::class); } } $permissions = User::find($id)->permissions;
Contributing
Please see CONTRIBUTING and CODE OF CONDUCT for details.
staudenmeir/eloquent-json-relations 适用场景与选型建议
staudenmeir/eloquent-json-relations 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.58M 次下载、GitHub Stars 达 1.08k, 最近一次更新时间为 2018 年 10 月 19 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 staudenmeir/eloquent-json-relations 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 staudenmeir/eloquent-json-relations 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 6.58M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1084
- 点击次数: 30
- 依赖项目数: 19
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-10-19