If you need to store additional attributes alongside your foreign keys in a JSON array (e.g., a pivot record with extra metadata), use the [] syntax in the relationship path.
In the BelongsToJson definition, the path should point to the array, and the key name should be the property inside the object.
Note: These relationships only work partially on SQLite and SQL Server.
Example Path: options->roles[]->role_id where options->roles is the array and role_id is the key inside each object.
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');
}
}
// Usage:
$user->roles()->attach([1 => ['active' => true], 2 => ['active' => false]])->save();
// Result: [{"role_id":1,"active":true},{"role_id":2,"active":false}]