Collections

QueryExecuter returns a collection when the result is multiple instance. The collection can be accessed like a php array. In addition, there are some useful methods like following:

Basic access

Basic access is operation on memory. There is no database access.

Fast loop

Loop with internal native array is faster than other ways. To get internal native array, use getNativeArray.

$customers = $qe->all();
$array = $customers->getNativeArray();
foreach($array as $obj) {
  // (omitted)
}

Add item

Add an item to the end of the collection.

$customers = $qe->all();
$customer = new Customer();
$customer->id = 0;
$customer->name = 'Takeshi';
$customers->add($customer);

Insert item

Insert an item to specific index.

$customers = $qe->all();
$customer = new Customer();
$customer->id = 0;
$customer->name = 'Takeshi';
$customers->insert(0, $customer);

Remove item

Remove the item with the specified index from the collection.

$customers = $qe->all();
$customers->remove(1);

Move item

Move the item at the specified index to the specified position in collection.

$customers = $qe->all();
$customers->move(0, $customers->count() - 1);

Renumbering row number

If the object has a property which holds line number, you can set the number by current sorting order. The number is 1-origin.

$customers = $qe->orderBy('name')->all();
$customers->renumber('row'); // property 'row' holds line number

Save and Delete on table

Collections generated as a result of a model relation can be saved and deleted in the table.

The following methods handle all items in collection at once.

Save

You can control how to save items with $options parameter of the method or $saveOprions property in collection.

Default is SAVE_AFTER_DELETE_ITEMS | DELETE_LOGICAL_ITEMS.

$tags->save(Collection::SAVE_WITHOUT_DELETE);

// or

$tags->$saveOprions = Collection::SAVE_WITHOUT_DELETE;
$tags->save();

When SAVE_ALL_BY_INSERT is specified, all items will be saved to the database by using bulkInsert. They will be inserted at high speed.

Note: When using bulkInsert, auto-incremented values will not be updated to the model. If you want to read the auto-incremented value, use refresh().