3.5. Records and Collections

The result of a fetchOne() call is a Solar_Sql_Model_Record object. Likewise, the result of a fetchAll() or fetchAssoc() call is a Solar_Sql_Model_Collection object.

3.5.1. Record Objects

The record object extends Solar_Struct, which itself implements ArrayAccess, Countable, and IteratorAggregate. This means that you can treat the record object much like an array when it's convenient.

<?php
// a single blog record, blog.id = 1
$item = $model->blogs->fetch(1);

// print the name and value of each property
foreach ($item as $col => $val) {
    $label = htmlspecialchars($col);
    $value = htmlspecialchars($val);
    echo "$label: $value<br />";
}

// echo the ID as a property or as an array element
echo $item->id . " is the same as " .  $item['id'];

You can also call any methods that exist on the record object; that would be the way to implement any record-level business logic for your domain.

3.5.2. Collection Objects

Like records, the collection object also extends Solar_Struct. This means that you can treat the collection much like an array when it's convenient.

<?php
// a collection of blog records
$list = $model->blogs->fetchAll();

// print the title of each blog entry.
// note that $n is a sequential array key,
// *not* the primary key value.
foreach ($list as $n => $blog) {
    echo "Primary key ID " . htmlspecialchars($blog->id)
       . " is titled " . htmlspecialchars($blog->title)
       . '<br />';
}

// how many records are in the collection?
$count = count($list);

// using fetchAssoc() will key the collection on the first
// column of the results. in this case, becasue 'id' is the
// first column, the array key and the primary key are the
// same thing.
$list = $model->blogs->fetchAssoc();
foreach ($list as $key => $blog) {
    echo "Primary key ID " . htmlspecialchars($blog->id)
       . " is the same as the assoc key " . htmlspecialchars($key)
       . '<br />';
}

[Note] Note

Collections receive all the data for their record objects at instantiation time, but they don't create a record object until you ask for it.

The collection object has a few methods that let you get information about the collection as a whole.

getPrimaryVals()

Returns an array of the unique primary keys contained in this collection. Does not trigger record object creation; it uses the internal results data array only.

getColVals($colname)

Returns an array of all values for a single column in the collection. This *does* trigger record object creation, since the requested column may be calculated as a magic __get() in the record objects.

getPagerInfo()

Gets the array of pager information for the collection. These values are set when you use the count_pages parameter on your fetch, and are suitable for passing directly to Solar_View_Helper_Pager (i.e., the helper for displaying pagination links). The pager info keys are described under Solar_Sql_Model_Collection::getPagerInfo().



Local