Oihana PHP Arango

DocumentsArrayTrait uses trait:short, trait:short, \oihana\models\traits\signals\HasUpdateSignals

Manage an **embedded array field** of an ArangoDB document — add, remove, move, reorder, edit in place, test membership — server-side, atomically, in a single AQL `UPDATE`.

This replaces the legacy ListItemTrait / MultiFieldTrait. The behaviour of a field (ordering, uniqueness, optional length counter) is declared once on the model through the arrays option (static::initializeArrays()), so callers never repeat unique/counter/sorted flags:

new Documents( $container,
[
    AQL::COLLECTION => 'Playlist',
    AQL::ARRAYS     =>
    [
        'tracks' => [ ArrayMode::LIST , Arango::COUNTER => 'numberOfTracks' , Arango::ITEM_KEY => 'id' ],
        'tags'   => ArrayMode::SET ,
        'genres' => ArrayMode::SORTED_SET ,
    ],
]);

Document identification follows the model convention: Arango::OWNER is the value that identifies the document, matched against the Arango::KEY attribute (default _key); Arango::VALUE is the array element(s) being added/removed/moved.

A field may additionally declare an Arango::ITEM_KEY — the attribute carried by each element that identifies it ('id' above). It makes Arango::VALUE the key of the element rather than the element itself, so an object can be targeted without resending it in full. Fields without an item key keep their by-value behaviour, and are the only ones arrayUpdate() refuses: an in-place edit needs a key.

All write methods emit the HasUpdateSignals beforeUpdate / afterUpdate signals, like the other write operations of the model.

Tags
see
ArrayMode
Side
ArangoTrait

Table of Contents

Constants

ARRAY_VAR  : string = '__arr'
The AQL variable holding the new array value written back by the `UPDATE`.
ELEMENT_VAR  : string = '__el'
The AQL variable holding the element targeted by an item key, looked up by {@see arrayMove()} before it rebuilds the final order.
INDEX_VAR  : string = '__i'
The AQL variable holding the index of the element being renumbered, bound by the loop {@see arrayRank()} runs over the final array.
KEY_VAR  : string = '__k'
The AQL variable holding the item key currently looked up by {@see arrayReorder()}, bound by the loop it runs over the requested order.
ORDERED_VAR  : string = '__ord'
The AQL variable holding the elements {@see arrayReorder()} resolved from the requested order, before the ones it did not mention are appended back.
RANKED_VAR  : string = '__pos'
The AQL variable holding the renumbered array — the one written back when the field declares an {@see Arango::POSITION_KEY}, in place of {@see self::ARRAY_VAR}.
REMAINDER_VAR  : string = '__rm'
The AQL variable holding the array **minus** the element being moved, from which {@see arrayMove()} rebuilds the final order.

Properties

$arrays  : array<string|int, mixed>
The per-field embedded-array configuration, normalised to `[ field => [ Arango::MODE => ArrayMode::*, Arango::COUNTER => ?string, Arango::ITEM_KEY => ?string, Arango::POSITION_KEY => ?string ] ]`.
$collection  : string|null
The default collection name.
$indexes  : array<string|int, mixed>|null
The declared indexes of the collection (the `AQL::INDEXES` list of {@see IndexOptions} or raw definitions). Retained at initialization — whether the lazy provisioning ran or not — so the declaration can be compared with the server later ({@see DoctorTrait::diagnose()}).
$arangodb  : ArangoDB|null
The ArangoDB database reference.
$type  : int
Indicates the type of the collection when is created (document or edge).

Methods

analyzerExists()  : bool
Checks if an analyzer exists on the server (built-in analyzers are always reported).
arrayContains()  : bool
Checks whether the array `field` of a single document (identified by `owner`) contains `value`.
arrayDefaults()  : array<string, array<string|int, mixed>|int>
Returns the default seed for the declared embedded array fields: each array field defaults to `[]`, and each declared counter to `0`.
arrayInsert()  : object|null
Adds one or several values to the array `field` of a single document.
arrayMove()  : object|null
Moves an existing `value` to the given zero-based `position` inside the array `field`.
arrayPurgeRef()  : array<string|int, object>|int
Removes a `value` from the array `field` of **every** document of the collection that contains it — typically to purge a now-deleted reference.
arrayRemove()  : object|null
Removes one or several values from the array `field` of a single document.
arrayReorder()  : object|null
Reorders the array `field` from a list of item keys — the whole new order in a single call, where {@see arrayMove()} moves one element at a time.
arrayUpdate()  : object|null
Merges a partial `patch` into the element of the array `field` carrying the given item key — an **in-place edit**, where the other operations only add, remove or reorder whole elements.
bind()  : string
Bind a value to an AQL query variable.
bindCollection()  : string
Bind a collection name to an AQL query variable.
bindView()  : string
Bind the model's declared View name (`AQL::VIEW` block, {@see Search::NAME}) to an AQL query variable — collection bind parameters (`@@view`) are valid for View names as well.
collectionCreate()  : bool
Creates a new collection if not exist.
collectionDrop()  : bool
Drops a collection if exist.
collectionExists()  : bool
Check if collection exists
collectionRename()  : bool
Renames a collection if exist.
collectionTruncate()  : bool
Truncate a collection if exist.
createIndex()  : array<string|int, mixed>|null
Creates an index on a collection on the server.
debugQuery()  : void
Debug the passed-in query and binds variables.
explain()  : ExplainResult
Explains an AQL query — returns the optimizer's execution plan as a typed {@see ExplainResult} (rules applied, collections, estimated cost, indexes actually used) **without executing the query**.
foundRows()  : int
For a SELECT with a LIMIT clause, returns the number of rows that would be returned were there no LIMIT clause.
getDatabase()  : ArangoDB
Returns the ArangoDB database singleton reference.
getDocuments()  : array<string|int, mixed>
Prepare, execute and returns an array of all documents with the passed-in AQL query.
getExtra()  : array<string|int, mixed>
Returns the AQL current extra datas.
getFirstResult()  : mixed
Prepare, execute and returns the first result of the passed-in AQL query.
getObject()  : object|null
Prepare, execute and returns an object with the passed-in AQL query.
getProfile()  : ProfileResult
Returns the typed profile of the last profiled query run (per-phase timings, {@see ExecutionStats}, warnings).
getResult()  : array<string|int, mixed>|null
Prepare, execute and returns an array with the passed-in AQL query.
getStats()  : ExecutionStats
Returns the typed execution statistics of the last query (scanned / filtered / time / memory …). Most meaningful right after a profiled `list()` / `get()` (see {@see Arango::PROFILE}).
initializeArrays()  : static
Initialize the per-field embedded-array configuration from the `arrays` option.
initializeCollection()  : static
Sets the internal collection reference.
initializeDatabase()  : static
Set the internal arangoDB reference.
initializeIndexes()  : static
Sets the declared indexes of the collection from the init definition, normalizing a single {@see IndexOptions} value to a one-element list (a raw array always stays the index list) — so every consumer sees a plain `IndexOptions[]`: the {@see initializeCollection()} lazy provisioning and the {@see DoctorTrait} diagnose/repair diffs.
prepareAndExecute()  : static
Prepare and execute an ArangoDB AQL query.
registerProperty()  : void
Register a specific dynamic property in the binds and values collection to generates a query.
streamDocuments()  : Generator<string|int, mixed>
Prepare, execute and returns a generator of documents with the passed-in AQL query.
viewCreate()  : bool
Creates an `arangosearch` View if it does not already exist.
viewExists()  : bool
Checks if a View exists.
arrayCounter()  : string|null
Returns the configured length-counter attribute of an array field, or null.
arrayItemKey()  : string|null
Resolves the item-key attribute of an array field — the attribute carried by each element that identifies it — honouring an optional per-call `itemKey` override, then the declared configuration, then defaulting to null.
arrayMode()  : string
Resolves the {@see ArrayMode} of an array field, honouring an optional per-call `mode` override, then the declared configuration, then defaulting to LIST.
arrayPositionKey()  : string|null
Resolves the position-key attribute of an array field — the attribute of each element carrying its rank — honouring an optional per-call `positionKey` override, then the declared configuration, then defaulting to null.
arrayWith()  : string
Builds the `WITH { ... }` object clause: the array field, its optional length counter, and the `modified` timestamp unless `touch` is disabled.
ensureArrayDefaults()  : Closure|null
Builds an `ensure` closure that seeds the declared array fields to `[]` (and their counters to `0`) for any missing key of a document being created, then applies the optional user-supplied `ensure`. Returns the user closure unchanged when no array field is declared (so models without `AQL::ARRAYS` are untouched).
firstRowAsArray()  : array<string|int, mixed>
Runs a single-row aggregate query and normalizes its result to an array.
profileOptions()  : array<string|int, mixed>
Merges the cursor `profile` option into `$options` when the `$init` array requests profiling via {@see Arango::PROFILE} (`true` → profile level 2, or an explicit integer level). Returns `$options` unchanged otherwise.
arrayErasedKeys()  : array<int, string>
The attributes a patch asks to be taken away — the keys it carries at null.
arrayRank()  : array{0: array, 1: string}
Appends the renumbering `LET` to the given clauses when the field declares an {@see Arango::POSITION_KEY}, and returns them along with the AQL variable holding the array to write back.
collectOptionalBindNames()  : array<int, string>
Collects every {@see AqlBindReference} name declared anywhere in one or more declaration trees — the projections (`$fields` / `$skinFields`) **and** the relation registries (`$edges` / `$joins`), typically inside a `Field::WHERE` / `Field::WHEN` condition. These are the *optional* binds : a skin (or an explicit `?fields`) can drop the carrying field — or the whole relation — from the projection, so the declared bind may not reach the final query text.
runArrayUpdate()  : object|null
Compiles and executes a single-document array UPDATE (`FOR ... FILTER ... LET ... UPDATE ... RETURN NEW`), emitting the update signals around the write.

Constants

ARRAY_VAR

The AQL variable holding the new array value written back by the `UPDATE`.

protected string ARRAY_VAR = '__arr'

Double-underscored to stay out of the way of any user-supplied bind or alias.

ELEMENT_VAR

The AQL variable holding the element targeted by an item key, looked up by {@see arrayMove()} before it rebuilds the final order.

protected string ELEMENT_VAR = '__el'

It is null when no element carries the requested key, which the move guards against so an unknown key is a no-op rather than a phantom insertion.

INDEX_VAR

The AQL variable holding the index of the element being renumbered, bound by the loop {@see arrayRank()} runs over the final array.

protected string INDEX_VAR = '__i'

KEY_VAR

The AQL variable holding the item key currently looked up by {@see arrayReorder()}, bound by the loop it runs over the requested order.

protected string KEY_VAR = '__k'

ORDERED_VAR

The AQL variable holding the elements {@see arrayReorder()} resolved from the requested order, before the ones it did not mention are appended back.

protected string ORDERED_VAR = '__ord'

RANKED_VAR

The AQL variable holding the renumbered array — the one written back when the field declares an {@see Arango::POSITION_KEY}, in place of {@see self::ARRAY_VAR}.

protected string RANKED_VAR = '__pos'

REMAINDER_VAR

The AQL variable holding the array **minus** the element being moved, from which {@see arrayMove()} rebuilds the final order.

protected string REMAINDER_VAR = '__rm'

Properties

$arrays

The per-field embedded-array configuration, normalised to `[ field => [ Arango::MODE => ArrayMode::*, Arango::COUNTER => ?string, Arango::ITEM_KEY => ?string, Arango::POSITION_KEY => ?string ] ]`.

public array<string|int, mixed> $arrays = []

$collection

The default collection name.

public string|null $collection

$indexes

The declared indexes of the collection (the `AQL::INDEXES` list of {@see IndexOptions} or raw definitions). Retained at initialization — whether the lazy provisioning ran or not — so the declaration can be compared with the server later ({@see DoctorTrait::diagnose()}).

public array<string|int, mixed>|null $indexes = null

$type

Indicates the type of the collection when is created (document or edge).

protected int $type

Methods

analyzerExists()

Checks if an analyzer exists on the server (built-in analyzers are always reported).

public analyzerExists(string $name) : bool
Parameters
$name : string

The name of the analyzer.

Return values
bool

arrayContains()

Checks whether the array `field` of a single document (identified by `owner`) contains `value`.

public arrayContains([array{owner?: mixed, field?: string, value?: mixed, key?: string, itemKey?: string, prefix?: string, debug?: bool} $init = [] ]) : bool

Generated AQL: RETURN LENGTH( FOR doc IN @@collection FILTER doc._key == @key && POSITION(doc.field, @value) RETURN 1 ) > 0

When the field declares an Arango::ITEM_KEY, value is the key of the element rather than the element itself and the membership test becomes doc.field[? FILTER CURRENT.<itemKey> == @value].

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, key?: string, itemKey?: string, prefix?: string, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
ValidationException
Return values
bool

True if the value is present.

arrayDefaults()

Returns the default seed for the declared embedded array fields: each array field defaults to `[]`, and each declared counter to `0`.

public arrayDefaults() : array<string, array<string|int, mixed>|int>

Used to initialize a freshly created document so that every declared array field is always a real (possibly empty) array — see ensureArrayDefaults().

Return values
array<string, array<string|int, mixed>|int>

e.g. [ 'tracks' => [], 'numberOfTracks' => 0, 'tags' => [] ].

arrayInsert()

Adds one or several values to the array `field` of a single document.

public arrayInsert([array{owner?: mixed, field?: string, value?: mixed, side?: string, mode?: string, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

The uniqueness and sorting are driven by the field's ArrayMode; value may be a scalar or an array (its elements are appended, never nested).

Generated AQL (LIST/SET, side RIGHT): ... UPDATE doc WITH { field: APPEND(doc.field, @value [, true]) [, counter: LENGTH(...)] [, modified: ...] } ...

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, side?: string, mode?: string, key?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
Return values
object|null

The updated document, or null if no document matched.

arrayMove()

Moves an existing `value` to the given zero-based `position` inside the array `field`.

public arrayMove([array{owner?: mixed, field?: string, value?: mixed, position?: int, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

Unsupported on a ArrayMode::SORTED_SET field (the sort order overrides any manual position): an UnsupportedOperationException is thrown.

Generated AQL:

LET __rm  = REMOVE_VALUE(doc.field, @value)
LET __arr = APPEND( PUSH( SLICE(__rm, 0, <pos>), @value, true ), SLICE(__rm, <pos>) )
UPDATE doc WITH { field: __arr [, counter: LENGTH(__arr)] [, modified: ...] } ...

When the field declares an Arango::ITEM_KEY, value is the key of the element to move; it is looked up first and the reordering is guarded on it:

LET __el  = FIRST(doc.field[* FILTER CURRENT.<itemKey> == @value])
LET __rm  = doc.field[* FILTER CURRENT.<itemKey> != @value]
LET __arr = __el == null ? doc.field : APPEND( PUSH( SLICE(__rm, 0, <pos>), __el, true ), SLICE(__rm, <pos>) )

A key matching no element therefore leaves the array untouched, rather than inserting a null at the requested position.

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, position?: int, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
UnsupportedOperationException
ValidationException
Return values
object|null

The updated document, or null if no document matched.

arrayPurgeRef()

Removes a `value` from the array `field` of **every** document of the collection that contains it — typically to purge a now-deleted reference.

public arrayPurgeRef([array{field?: string, value?: mixed, prefix?: string, touch?: bool, count?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : array<string|int, object>|int

Generated AQL: FOR doc IN @@collection FILTER POSITION(doc.field, @value) LET __arr = REMOVE_VALUE(doc.field, @value) UPDATE doc WITH { ... } ... RETURN NEW

Unlike the single-document operations, this one is by value only: it ignores any declared Arango::ITEM_KEY and matches the reference structurally.

Parameters
$init : array{field?: string, value?: mixed, prefix?: string, touch?: bool, count?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
Return values
array<string|int, object>|int

The list of modified documents, or their count when count is true.

arrayRemove()

Removes one or several values from the array `field` of a single document.

public arrayRemove([array{owner?: mixed, field?: string, value?: mixed, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

Generated AQL (scalar value): ... UPDATE doc WITH { field: REMOVE_VALUE(doc.field, @value) [, counter: LENGTH(...)] [, modified: ...] } ... (an array value uses REMOVE_VALUES instead).

When the field declares an Arango::ITEM_KEY, value holds the key(s) of the element(s) to drop and the new array is the inline filter doc.field[* FILTER CURRENT.<itemKey> != @value] (NOT IN for a list of keys).

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
ValidationException
Return values
object|null

The updated document, or null if no document matched.

arrayReorder()

Reorders the array `field` from a list of item keys — the whole new order in a single call, where {@see arrayMove()} moves one element at a time.

public arrayReorder([array{owner?: mixed, field?: string, value?: mixed, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

Generated AQL:

LET __ord = (FOR __k IN @value LET __el = FIRST(doc.field[* FILTER CURRENT.<itemKey> == __k]) FILTER __el != null RETURN __el)
LET __arr = APPEND(__ord, doc.field[* FILTER CURRENT.<itemKey> NOT IN @value])
UPDATE doc WITH { field: __arr [, counter: LENGTH(__arr)] [, modified: ...] } ...

The elements the list does not mention are kept and appended after it: a partial list reorders what it names instead of deleting the rest. A key matching no element is skipped, and an empty list leaves the array as it is.

Duplicate keys are collapsed (first occurrence wins) before the query is built — resolving the same key twice would otherwise duplicate its element.

Requires an item key, like arrayUpdate(): without an attribute identifying the elements there is nothing to order them by. Unsupported on a ArrayMode::SORTED_SET field, like arrayMove().

Being a permutation of the existing elements, it does not re-apply the field invariant — it cannot introduce a duplicate that was not already there.

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
UnsupportedOperationException
ValidationException
Return values
object|null

The updated document, or null if no document matched.

arrayUpdate()

Merges a partial `patch` into the element of the array `field` carrying the given item key — an **in-place edit**, where the other operations only add, remove or reorder whole elements.

public arrayUpdate([array{owner?: mixed, field?: string, value?: mixed, patch?: array|object, eraseNull?: bool, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} $init = [] ]) : object|null

Generated AQL:

LET __arr = doc.field[* RETURN CURRENT.<itemKey> == @value ? MERGE(CURRENT, @patch) : CURRENT]
UPDATE doc WITH { field: __arr [, counter: LENGTH(__arr)] [, modified: ...] } ...

Every element is projected back, so a value matching none of them rewrites the array unchanged. The merge is partial: the patch attributes overwrite theirs, the others are kept.

🔑 A null does not erase, unless asked to. MERGE() keeps it: a patch saying { "reason": null } writes the attribute back as null rather than taking it away, so an element rebuilt in place can never lose an attribute it once carried. Pass Arango::ERASE_NULL to read those nulls as erasures instead — the merged element is then wrapped in an UNSET() of their keys:

LET __arr = doc.field[* RETURN CURRENT.<itemKey> == @value ? UNSET(MERGE(CURRENT, @patch), "reason") : CURRENT]

Top-level attributes only, like UNSET() itself: a null sitting inside a sub-object of the patch stays a value. The flag is opt-in, so an existing caller keeps its nulls.

Requires an item key — declared on the field or passed per call. A field targeted by value cannot be edited in place: designating its element would mean holding a byte-for-byte copy of it, which the very patch being applied invalidates, so an UnsupportedOperationException is thrown rather than emitting an operation that only works once.

The field invariant is re-applied afterwards, since a patch can make two elements equal: ArrayMode::SET wraps the result in UNIQUE(), ArrayMode::SORTED_SET in SORTED_UNIQUE().

Parameters
$init : array{owner?: mixed, field?: string, value?: mixed, patch?: array|object, eraseNull?: bool, key?: string, itemKey?: string, prefix?: string, touch?: bool, options?: array|object|string|null, debug?: bool} = []
Tags
throws
ArangoException
BindException
ContainerExceptionInterface
DependencyException
NotFoundException
NotFoundExceptionInterface
ReflectionException
Throwable
UnsupportedOperationException
ValidationException
Return values
object|null

The updated document, or null if no document matched.

bind()

Bind a value to an AQL query variable.

public bind(mixed $value[, array<string|int, mixed> &$binds = [] ][, string|null $to = null ]) : string
Parameters
$value : mixed

The value to bind to the query.

$binds : array<string|int, mixed> = []

Reference to the array of existing bind variables.

$to : string|null = null

Optional name of the bind variable. If null, a unique name is generated.

Tags
throws
BindException

If the provided bind variable name is invalid.

Return values
string

The formatted bind variable (including the "@" prefix as needed) for use in the query.

bindCollection()

Bind a collection name to an AQL query variable.

public bindCollection([array<string|int, mixed> &$binds = [] ][, array<string|int, mixed> $init = [] ]) : string

Prepares a bind variable for a collection name. Uses the collection defined in $init or falls back to $this->collection if none is provided.

Parameters
$binds : array<string|int, mixed> = []

Reference to the array of existing bind variables. If null, a new array is used.

$init : array<string|int, mixed> = []

Optional initialization array with keys:

  • Arango::COLLECTION => the collection name to bind
  • Arango::NAME => optional bind variable name
Tags
throws
BindException

If the bind variable name is invalid.

Return values
string

The formatted bind variable representing the collection.

bindView()

Bind the model's declared View name (`AQL::VIEW` block, {@see Search::NAME}) to an AQL query variable — collection bind parameters (`@@view`) are valid for View names as well.

public bindView([array<string|int, mixed> &$binds = [] ]) : string
Parameters
$binds : array<string|int, mixed> = []

Reference to the array of existing bind variables.

Tags
throws
BindException

If the bind variable name is invalid.

Return values
string

The formatted bind variable representing the View.

collectionCreate()

Creates a new collection if not exist.

public collectionCreate(string $name[, array<string|int, mixed> $options = [] ]) : bool
Parameters
$name : string

The name of the new collection

$options : array<string|int, mixed> = []
  • an array of options.

Options are:

  • 'type' - 2 -> normal collection, 3 -> edge-collection
  • 'waitForSync' - if set to true, then all removal operations will instantly be synchronised to disk / If this is not specified, then the collection's default sync behavior will be applied.
  • 'isSystem' - false->user collection(default), true->system collection .
  • 'keyOptions' - key options to use.
  • 'distributeShardsLike' - name of prototype collection for identical sharding.
  • 'numberOfShards' - number of shards for the collection.
  • 'replicationFactor' - number of replicas to keep (default: 1).
  • 'writeConcern' - minimum number of replicas to be successful when writing (default: 1).
  • 'shardKeys' - array of shard key attributes.
  • 'shardingStrategy' - sharding strategy to use in cluster.
  • 'smartJoinAttribute' - attribute name for smart joins (if not shard key).
  • 'schema' - collection schema.
  • Return values
    bool

    Returns true if the new collection is created.

    collectionDrop()

    Drops a collection if exist.

    public collectionDrop(string $name) : bool
    Parameters
    $name : string

    The name of the new collection

    Return values
    bool

    Returns true if the new collection is dropped.

    collectionExists()

    Check if collection exists

    public collectionExists(string $name) : bool
    Parameters
    $name : string

    The name of the collection

    Return values
    bool

    collectionRename()

    Renames a collection if exist.

    public collectionRename(string $oldName, string $name) : bool
    Parameters
    $oldName : string

    The old name of the collection

    $name : string

    The new name of the collection

    Tags
    throws
    ArangoException
    Return values
    bool

    Returns true if the collection is renamed.

    collectionTruncate()

    Truncate a collection if exist.

    public collectionTruncate(string $name) : bool
    Parameters
    $name : string

    The name of the collection to truncate.

    Return values
    bool

    createIndex()

    Creates an index on a collection on the server.

    public createIndex(string|Collection $collection, array<string|int, mixed>|IndexOptions $indexOptions) : array<string|int, mixed>|null
    Parameters
    $collection : string|Collection

    Collection name or Collection client handle.

    $indexOptions : array<string|int, mixed>|IndexOptions

    An IndexOptions definition or an associative array of options for the index like array('type' => 'persistent', 'fields' => ['id','additionalType'], 'sparse' => false)

    Tags
    throws
    ReflectionException
    Return values
    array<string|int, mixed>|null

    The server response of the created index or null

    debugQuery()

    Debug the passed-in query and binds variables.

    public debugQuery(string $method, string $query, array<string|int, mixed>|null $binds) : void
    Parameters
    $method : string
    $query : string
    $binds : array<string|int, mixed>|null

    explain()

    Explains an AQL query — returns the optimizer's execution plan as a typed {@see ExplainResult} (rules applied, collections, estimated cost, indexes actually used) **without executing the query**.

    public explain(AqlQuery|string $query[, array<string, mixed> $bindVars = [] ][, array<string, mixed> $options = [] ]) : ExplainResult
    Parameters
    $query : AqlQuery|string

    The AQL query to explain.

    $bindVars : array<string, mixed> = []

    Bind variables (omit when $query is an AqlQuery).

    $options : array<string, mixed> = []

    Explain options (allPlans, optimizer.rules, …).

    Tags
    throws
    ArangoException
    Return values
    ExplainResult

    foundRows()

    For a SELECT with a LIMIT clause, returns the number of rows that would be returned were there no LIMIT clause.

    public foundRows() : int
    Return values
    int

    getDocuments()

    Prepare, execute and returns an array of all documents with the passed-in AQL query.

    public getDocuments(string $query[, array<string|int, mixed> $bindVars = [] ][, array<string|int, mixed> $options = [] ][, bool $raw = false ][, null|SchemaResolver|Closure|string $schema = null ][, array<string|int, mixed> $context = [] ]) : array<string|int, mixed>
    Parameters
    $query : string

    The AQL query string to execute

    $bindVars : array<string|int, mixed> = []

    Optional bind variables for the query

    $options : array<string|int, mixed> = []

    Optional execution options

    $raw : bool = false

    If true, returns the object raw (no schema or alter applied)

    $schema : null|SchemaResolver|Closure|string = null

    The optional class name to map the document.

    $context : array<string|int, mixed> = []

    Optional opaque context forwarded to AlterDocumentTrait::alter() and thus to the Alter::MAP callbacks (e.g. the originating $init, a skin, a locale…). Default [].

    Tags
    throws
    ArangoException
    ContainerExceptionInterface
    DependencyException
    NotFoundException
    NotFoundExceptionInterface
    ReflectionException
    Return values
    array<string|int, mixed>

    getExtra()

    Returns the AQL current extra datas.

    public getExtra() : array<string|int, mixed>
    Return values
    array<string|int, mixed>

    getFirstResult()

    Prepare, execute and returns the first result of the passed-in AQL query.

    public getFirstResult(string $query[, array<string|int, mixed> $bindVars = [] ][, array<string|int, mixed> $options = [] ][, bool $raw = false ][, null|SchemaResolver|Closure|string $schema = null ][, array<string|int, mixed> $context = [] ]) : mixed
    Parameters
    $query : string

    The AQL query string to execute

    $bindVars : array<string|int, mixed> = []

    Optional bind variables for the query

    $options : array<string|int, mixed> = []

    Optional execution options

    $raw : bool = false

    If true, returns the object raw (no schema or alter applied)

    $schema : null|SchemaResolver|Closure|string = null

    The optional class name to map the document.

    $context : array<string|int, mixed> = []

    Optional opaque context forwarded to AlterDocumentTrait::alter() and thus to the Alter::MAP callbacks (e.g. the originating $init, a skin, a locale…). Default [].

    Tags
    throws
    ArangoException
    ContainerExceptionInterface
    DependencyException
    NotFoundException
    NotFoundExceptionInterface
    ReflectionException

    getObject()

    Prepare, execute and returns an object with the passed-in AQL query.

    public getObject(string $query[, array<string|int, mixed> $bindVars = [] ][, array<string|int, mixed> $options = [] ][, bool $raw = false ][, null|SchemaResolver|Closure|string $schema = null ][, array<string|int, mixed> $context = [] ]) : object|null
    Parameters
    $query : string

    The AQL query string to execute

    $bindVars : array<string|int, mixed> = []

    Optional bind variables for the query

    $options : array<string|int, mixed> = []

    Optional execution options

    $raw : bool = false

    If true, returns the object raw (no schema or alter applied)

    $schema : null|SchemaResolver|Closure|string = null

    The optional class name to map the document.

    $context : array<string|int, mixed> = []

    Optional opaque context forwarded to AlterDocumentTrait::alter() and thus to the Alter::MAP callbacks (e.g. the originating $init, a skin, a locale…). Default [].

    Tags
    throws
    ArangoException
    ContainerExceptionInterface
    NotFoundExceptionInterface
    ReflectionException
    DependencyException
    NotFoundException
    Return values
    object|null

    getProfile()

    Returns the typed profile of the last profiled query run (per-phase timings, {@see ExecutionStats}, warnings).

    public getProfile() : ProfileResult
    Return values
    ProfileResult

    getResult()

    Prepare, execute and returns an array with the passed-in AQL query.

    public getResult(string $query[, array<string|int, mixed> $bindVars = [] ][, array<string|int, mixed> $options = [] ][, bool $raw = false ][, null|SchemaResolver|Closure|string $schema = null ][, array<string|int, mixed> $context = [] ]) : array<string|int, mixed>|null
    Parameters
    $query : string

    The AQL query string to execute

    $bindVars : array<string|int, mixed> = []

    Optional bind variables for the query

    $options : array<string|int, mixed> = []

    Optional execution options

    $raw : bool = false

    If true, returns the object raw (no schema or alter applied)

    $schema : null|SchemaResolver|Closure|string = null

    The optional class name to map the document.

    $context : array<string|int, mixed> = []

    Optional opaque context forwarded to AlterDocumentTrait::alter() and thus to the Alter::MAP callbacks (e.g. the originating $init, a skin, a locale…). Default [].

    Tags
    throws
    ArangoException
    ContainerExceptionInterface
    DependencyException
    NotFoundException
    NotFoundExceptionInterface
    ReflectionException
    Return values
    array<string|int, mixed>|null

    getStats()

    Returns the typed execution statistics of the last query (scanned / filtered / time / memory …). Most meaningful right after a profiled `list()` / `get()` (see {@see Arango::PROFILE}).

    public getStats() : ExecutionStats
    Return values
    ExecutionStats

    initializeArrays()

    Initialize the per-field embedded-array configuration from the `arrays` option.

    public initializeArrays([array<string|int, mixed> $init = [] ]) : static

    Each entry is either an ArrayMode shorthand ('tags' => ArrayMode::SET) or a richer definition ('tracks' => [ ArrayMode::LIST , Arango::COUNTER => 'numberOfTracks' ]).

    Parameters
    $init : array<string|int, mixed> = []
    Return values
    static

    initializeCollection()

    Sets the internal collection reference.

    public initializeCollection([array<string|int, mixed> $init = [] ][, int $type = CollectionType::DOCUMENT ]) : static
    Parameters
    $init : array<string|int, mixed> = []

    The options to lazy creates the collection (document or edge) or not.

    • collection (string) Indicates if the name of the collection.
    • indexes (array) The optional list of indexes to creates (if not exist and lazy).
    • lazy (bool) Indicates if the collection is created if not exist — resolved through LazyTrait::isLazy(), so a lazy entry defined in the DI container always wins (orchestration kill-switch), then this init key, then the property default.
    • options (array) The options are:
      • 'waitForSync' : if set to true, then all removal operations will instantly be synchronised to disk / If this is not specified, then the collection's default sync behavior will be applied.
      • 'isSystem' : false->user collection(default), true->system collection .
      • 'keyOptions' : key options to use.
      • 'distributeShardsLike' : name of prototype collection for identical sharding.
      • 'numberOfShards' : number of shards for the collection.
      • 'replicationFactor' : number of replicas to keep (default: 1).
      • 'writeConcern' : minimum number of replicas to be successful when writing (default: 1).
      • 'shardKeys' : array of shard key attributes.
      • 'shardingStrategy' : sharding strategy to use in cluster.
      • 'smartJoinAttribute' : attribute name for smart joins (if not shard key).
      • 'schema' : collection schema.
    $type : int = CollectionType::DOCUMENT

    The default type of the collection (Default -> 'document' [2] )

    Tags
    throws
    ContainerExceptionInterface

    If an error occurs while reading the container lazy entry.

    NotFoundExceptionInterface

    If the container lazy entry vanishes between check and read.

    ReflectionException
    Return values
    static

    initializeDatabase()

    Set the internal arangoDB reference.

    public initializeDatabase([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
    Parameters
    $init : array<string|int, mixed> = []
    $container : ContainerInterface|null = null
    Tags
    throws
    ContainerExceptionInterface
    NotFoundExceptionInterface
    Return values
    static

    initializeIndexes()

    Sets the declared indexes of the collection from the init definition, normalizing a single {@see IndexOptions} value to a one-element list (a raw array always stays the index list) — so every consumer sees a plain `IndexOptions[]`: the {@see initializeCollection()} lazy provisioning and the {@see DoctorTrait} diagnose/repair diffs.

    public initializeIndexes([array<string|int, mixed> $init = [] ]) : static
    Parameters
    $init : array<string|int, mixed> = []

    The init definition (reads the Arango::INDEXES key).

    Return values
    static

    prepareAndExecute()

    Prepare and execute an ArangoDB AQL query.

    public prepareAndExecute(string $query[, array<string|int, mixed> $bindVars = [] ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed>|null $optionalBinds = null ]) : static

    A bind variable may be optional : supplied by the caller (through Arango::BINDS) yet not guaranteed to appear in the final query text. This happens with a conditional projection — e.g. an aqlBindRef() inside a Field::WHERE / Field::WHEN carried by a field that the active skin (or an explicit ?fields) does not project. ArangoDB rejects a query that declares a bind it never references ("bind parameter 'x' was not declared in the query"), so such a leftover bind must be dropped before execution.

    $optionalBinds names the binds that are allowed to be absent :

    • it is opt-in and bounded — a bind whose name is not listed is never touched, so a query that uses no conditional bind behaves exactly as before ;
    • a listed bind is kept only when the query actually references it (@name, word-boundary matched to avoid a prefix collision such as @offers matching inside @offersScope) ;
    • passing [] disables the pruning explicitly.

    When $optionalBinds is null (the default), the list is derived from the model's own declarations — every AqlBindReference found anywhere in $this->fields / $this->skinFields and in the relation registries $this->edges / $this->joins (see collectOptionalBindNames()). The registries matter as much as the projections: a relation definition is a declaration tree of its own, it can carry a conditional bind (in its own AQL::FIELDS sub-projection, or in a definition-level predicate), and a skin dropping the relation leaves that bind unreferenced exactly the same way. The source of truth is the same aqlBindRef() that declared the conditional bind, so no host wiring is required, and over-listing a bind that turns out to be always present is inert (a referenced bind is always kept). Because this runs at the single execution chokepoint, it protects every query method (get(), list(), count(), exist(), edges…) uniformly.

    Parameters
    $query : string

    The AQL query string to execute.

    $bindVars : array<string|int, mixed> = []

    Optional bind variables for the query.

    $options : array<string|int, mixed> = []

    Optional execution options.

    $optionalBinds : array<string|int, mixed>|null = null

    Names of binds allowed to be absent from the query. null derives the list from the model field definitions and relation registries ; [] disables the pruning.

    Tags
    throws
    ArangoException
    Return values
    static

    registerProperty()

    Register a specific dynamic property in the binds and values collection to generates a query.

    public registerProperty(string $name, mixed $value, array<string|int, mixed> &$binds, array<string|int, mixed> &$values[, string $prefix = Char::EMPTY ][, string $separator = ': ' ]) : void
    Parameters
    $name : string
    $value : mixed
    $binds : array<string|int, mixed>
    $values : array<string|int, mixed>
    $prefix : string = Char::EMPTY
    $separator : string = ': '

    streamDocuments()

    Prepare, execute and returns a generator of documents with the passed-in AQL query.

    public streamDocuments(string $query[, array<string|int, mixed> $bindVars = [] ][, array<string|int, mixed> $options = [] ][, bool $raw = false ][, null|SchemaResolver|Closure|string $schema = null ][, array<string|int, mixed> $context = [] ]) : Generator<string|int, mixed>

    Documents are yielded one by one, allowing efficient memory usage for large result sets.

    Parameters
    $query : string

    The AQL query string to execute

    $bindVars : array<string|int, mixed> = []

    Optional bind variables for the query

    $options : array<string|int, mixed> = []

    Optional execution options

    $raw : bool = false

    If true, returns the object raw (no schema or alter applied)

    $schema : null|SchemaResolver|Closure|string = null

    The optional class name to map the document.

    $context : array<string|int, mixed> = []

    Optional opaque context forwarded to AlterDocumentTrait::alter() and thus to the Alter::MAP callbacks (e.g. the originating $init, a skin, a locale…). Default [].

    Tags
    throws
    ArangoException
    ContainerExceptionInterface
    DependencyException
    NotFoundException
    NotFoundExceptionInterface
    ReflectionException
    Return values
    Generator<string|int, mixed>

    Generator yielding documents one by one

    viewCreate()

    Creates an `arangosearch` View if it does not already exist.

    public viewCreate(string $name[, array<string|int, mixed> $links = [] ][, array<string|int, mixed> $options = [] ]) : bool
    Parameters
    $name : string

    The name of the new View.

    $links : array<string|int, mixed> = []

    Per-collection link map (collection name → link definition).

    $options : array<string|int, mixed> = []

    Extra arangosearch options forwarded verbatim.

    Return values
    bool

    Returns true if the new View has been created.

    viewExists()

    Checks if a View exists.

    public viewExists(string $name) : bool
    Parameters
    $name : string

    The name of the View.

    Return values
    bool

    arrayCounter()

    Returns the configured length-counter attribute of an array field, or null.

    protected arrayCounter(string|null $field) : string|null
    Parameters
    $field : string|null
    Return values
    string|null

    arrayItemKey()

    Resolves the item-key attribute of an array field — the attribute carried by each element that identifies it — honouring an optional per-call `itemKey` override, then the declared configuration, then defaulting to null.

    protected arrayItemKey(string|null $field[, array<string|int, mixed> $init = [] ]) : string|null

    A null result means the field is targeted by value (the historical behaviour); a non-null one switches the element-level operations to a key match.

    The resolved name is interpolated verbatim into the generated AQL (the array expansion helpers do no escaping), so it is validated here — whatever its origin — against assertAttributeName().

    Parameters
    $field : string|null
    $init : array<string|int, mixed> = []
    Tags
    throws
    ValidationException

    When the configured item key is not a safe attribute name.

    Return values
    string|null

    The validated item-key attribute, or null when the field is targeted by value.

    arrayMode()

    Resolves the {@see ArrayMode} of an array field, honouring an optional per-call `mode` override, then the declared configuration, then defaulting to LIST.

    protected arrayMode(string|null $field[, array<string|int, mixed> $init = [] ]) : string
    Parameters
    $field : string|null
    $init : array<string|int, mixed> = []
    Return values
    string

    arrayPositionKey()

    Resolves the position-key attribute of an array field — the attribute of each element carrying its rank — honouring an optional per-call `positionKey` override, then the declared configuration, then defaulting to null.

    protected arrayPositionKey(string|null $field[, array<string|int, mixed> $init = [] ]) : string|null

    A null result means the field is never renumbered (the historical behaviour); a non-null one makes every write rewrite that attribute from the element indices.

    The resolved name is interpolated verbatim into the generated AQL, so it is validated here — whatever its origin — against assertAttributeName(). It is additionally required to be a flat name: unlike an item key, which is only ever read, a position key is written back, and a dotted path would produce a single attribute literally named meta.position instead of a nested one.

    Parameters
    $field : string|null
    $init : array<string|int, mixed> = []
    Tags
    throws
    ValidationException

    When the configured position key is not a safe flat attribute name.

    Return values
    string|null

    The validated position-key attribute, or null when the field is not renumbered.

    arrayWith()

    Builds the `WITH { ... }` object clause: the array field, its optional length counter, and the `modified` timestamp unless `touch` is disabled.

    protected arrayWith(string|null $field, string $arrayVar[, array<string|int, mixed> $init = [] ]) : string
    Parameters
    $field : string|null

    The array attribute name.

    $arrayVar : string

    The AQL variable holding the new array (see self::ARRAY_VAR).

    $init : array<string|int, mixed> = []
    Return values
    string

    ensureArrayDefaults()

    Builds an `ensure` closure that seeds the declared array fields to `[]` (and their counters to `0`) for any missing key of a document being created, then applies the optional user-supplied `ensure`. Returns the user closure unchanged when no array field is declared (so models without `AQL::ARRAYS` are untouched).

    protected ensureArrayDefaults([Closure|null $ensure = null ]) : Closure|null
    Parameters
    $ensure : Closure|null = null

    An optional user ensure closure to compose with.

    Return values
    Closure|null

    firstRowAsArray()

    Runs a single-row aggregate query and normalizes its result to an array.

    protected firstRowAsArray(string $query[, array<string|int, mixed> $bindVars = [] ]) : array<string|int, mixed>

    The aggregate queries — DocumentsBoundsTrait::bounds(), DocumentsFacetCountsTrait::facetCounts() — all return one row holding one entry per requested dimension, and all face the same two shapes: their builder yields an empty string when nothing is computable, and the row itself comes back as an object or as an array depending on how the driver decoded it. Both are handled here rather than at each call site.

    The result is read raw — no schema, no alter() — because the row is a map of computed values, not a document.

    Parameters
    $query : string

    The compiled aggregate query, or an empty string when there is nothing to compute.

    $bindVars : array<string|int, mixed> = []

    The bind variables of that query.

    Tags
    throws
    ArangoException
    ContainerExceptionInterface
    DependencyException
    NotFoundException
    NotFoundExceptionInterface
    ReflectionException
    Return values
    array<string|int, mixed>

    The single row as an associative array; an empty array when the query is empty or the row is neither an object nor an array.

    profileOptions()

    Merges the cursor `profile` option into `$options` when the `$init` array requests profiling via {@see Arango::PROFILE} (`true` → profile level 2, or an explicit integer level). Returns `$options` unchanged otherwise.

    protected profileOptions(array<string|int, mixed> $init[, array<string|int, mixed> $options = [] ]) : array<string|int, mixed>
    Parameters
    $init : array<string|int, mixed>

    The model input array (list() / get()).

    $options : array<string|int, mixed> = []

    The cursor options to augment.

    Return values
    array<string|int, mixed>

    arrayErasedKeys()

    The attributes a patch asks to be taken away — the keys it carries at null.

    private arrayErasedKeys(mixed $patch) : array<int, string>

    Only the top level is read, like AQL UNSET() itself: a null sitting inside a sub-object of the patch is a value, not an erasure. An element loses one whole attribute at a time, never half of one.

    🚨 The names are interpolated verbatim into the generated AQL — UNSET() takes string literals, not binds — so each one goes through the same guard as every other attribute name this trait emits. A patch carrying an integer key (a list cast to an object) names no attribute and is skipped.

    Parameters
    $patch : mixed

    The patch handed to self::arrayUpdate().

    Tags
    throws
    ValidationException

    When a key is not a safe flat attribute name.

    Return values
    array<int, string>

    The attribute names to remove, possibly empty.

    arrayRank()

    Appends the renumbering `LET` to the given clauses when the field declares an {@see Arango::POSITION_KEY}, and returns them along with the AQL variable holding the array to write back.

    private arrayRank(string|null $field, array<string|int, mixed> $lets, array<string|int, mixed> $init) : array{0: array, 1: string}

    Generated AQL:

    LET __pos = LENGTH(__arr) == 0 ? [] : (FOR __i IN 0 .. LENGTH(__arr) - 1 RETURN MERGE(NTH(__arr,__i),{ position: __i }))
    

    It always runs last, on the array every operation has already produced: the field invariant is therefore applied before the ranks, which matters on a ArrayMode::SET — renumbering makes every element distinct, so a UNIQUE() running after it would no longer collapse anything. For the same reason, a patch carrying the position attribute loses against the renumbering.

    The empty-array branch is not cosmetic: 0 .. LENGTH(__arr) - 1 becomes 0 .. -1 on an empty array, which AQL reads as a descending range and expands to [0, -1] — two phantom elements would be ranked into the document.

    Shared by runArrayUpdate() and arrayPurgeRef(), which compiles its own collection-wide query: a purge would otherwise leave gaps in the numbering.

    Parameters
    $field : string|null

    The array attribute name.

    $lets : array<string|int, mixed>

    The clauses produced by the operation, ending with self::ARRAY_VAR.

    $init : array<string|int, mixed>
    Tags
    throws
    ReflectionException
    UnsupportedOperationException

    On a sortedSet field (the ranks would feed the sort back).

    ValidationException

    When the configured position key is not a safe flat attribute name.

    Return values
    array{0: array, 1: string}

    The clauses, and the variable holding the array to write.

    collectOptionalBindNames()

    Collects every {@see AqlBindReference} name declared anywhere in one or more declaration trees — the projections (`$fields` / `$skinFields`) **and** the relation registries (`$edges` / `$joins`), typically inside a `Field::WHERE` / `Field::WHEN` condition. These are the *optional* binds : a skin (or an explicit `?fields`) can drop the carrying field — or the whole relation — from the projection, so the declared bind may not reach the final query text.

    private collectOptionalBindNames(array<string|int, mixed> ...$trees) : array<int, string>

    The walk is recursive and depth-agnostic : it descends into Field::FIELDS, edges and joins sub-definitions, and picks up a bind reference wherever it sits. Non-array leaves are visited but ignored, so a registry holding a resolved model instance or a callable is harmless. Collecting the raw (un-skinned) definitions is intentional — the superset of all possibly-optional binds is exactly what the execution layer must be allowed to prune.

    Parameters
    $trees : array<string|int, mixed>

    One or more declaration arrays to scan.

    Return values
    array<int, string>

    The de-duplicated list of bind names.

    runArrayUpdate()

    Compiles and executes a single-document array UPDATE (`FOR ... FILTER ... LET ... UPDATE ... RETURN NEW`), emitting the update signals around the write.

    private runArrayUpdate(string|null $field, array<string|int, mixed> $lets, string $filter, array<string|int, mixed> &$binds, array<string|int, mixed> $init) : object|null
    Parameters
    $field : string|null

    The array attribute name.

    $lets : array<string|int, mixed>

    The ordered LET clauses producing the self::ARRAY_VAR variable.

    $filter : string

    The FILTER predicate locating the document.

    $binds : array<string|int, mixed>

    The bind variables (mutated by reference).

    $init : array<string|int, mixed>
    Tags
    throws
    ArangoException
    BindException
    ContainerExceptionInterface
    DependencyException
    NotFoundException
    NotFoundExceptionInterface
    ReflectionException
    Throwable
    Return values
    object|null
    On this page

    Search results