Class AkActiveRecord

(line 184)

Description

AkObject
   |
   --AkBaseModel
      |
      --AkAssociatedActiveRecord
         |
         --AkActiveRecord

Located in File: /AkActiveRecord.php

Active Record objects doesn't specify their attributes directly, but rather infer them from the table definition with which they're linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.

See the mapping rules in table_name and the full example in README.txt for more insight.

== Creation ==

Active Records accepts constructor parameters either in an array or as a list of parameters in a specific format. The array method is especially useful when you're receiving the data from somewhere else, like a HTTP request. It works like this:

  1.    $user = new User(array('name' => 'David''occupation' => 'Code Artist'));
  2.    echo $user->name// Will print "David"

You can also use a parameter list initialization.:

$user = new User('name->', 'David', 'occupation->', 'Code Artist');

And of course you can just create a bare object and specify the attributes after the fact:

  1.    $user = new User();
  2.    $user->name = 'David';
  3.    $user->occupation = 'Code Artist';

== Conditions ==

Conditions can either be specified as a string or an array representing the WHERE-part of an SQL statement. The array form is to be used when the condition input is tainted and requires sanitization. The string form can be used for statements that doesn't involve tainted data. Examples:

  1.    class User extends ActiveRecord
  2.    {
  3.      function authenticateUnsafely($user_name$password)
  4.      {
  5.           return findFirst("user_name = '$user_name' AND password = '$password'");
  6.      }
  7.  
  8.      function authenticateSafely($user_name$password)
  9.      {
  10.           return findFirst("user_name = ? AND password = ?"$user_name$password);
  11.      }
  12.     }

The <tt>authenticateUnsafely</tt> method inserts the parameters directly into the query and is thus susceptible to SQL-injection attacks if the <tt>$user_name</tt> and <tt>$password</tt> parameters come directly from a HTTP request. The <tt>authenticateSafely</tt> method, on the other hand, will sanitize the <tt>$user_name</tt> and <tt>$password</tt> before inserting them in the query, which will ensure that an attacker can't escape the query and fake the login (or worse).

When using multiple parameters in the conditions, it can easily become hard to read exactly what the fourth or fifth question mark is supposed to represent. In those cases, you can resort to named bind variables instead. That's done by replacing the question marks with symbols and supplying a hash with values for the matching symbol keys:

  1.    $Company->findFirst(
  2.               "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
  3.                array(':id' => 3':name' => "37signals"':division' => "First"':accounting_date' => '2005-01-01')
  4.              );

== Accessing attributes before they have been type casted ==

Some times you want to be able to read the raw attribute data without having the column-determined type cast run its course first. That can be done by using the <attribute>_before_type_cast accessors that all attributes have. For example, if your Account model has a balance attribute, you can call $Account->balance_before_type_cast or $Account->id_before_type_cast.

This is especially useful in validation situations where the user might supply a string for an integer field and you want to display the original string back in an error message. Accessing the attribute normally would type cast the string to 0, which isn't what you want.

== Saving arrays, hashes, and other non-mappable objects in text columns ==

Active Record can serialize any object in text columns. To do so, you must specify this with by setting the attribute serialize with a comma separated list of columns or an array. This makes it possible to store arrays, hashes, and other non-mappeable objects without doing any additional work. Example:

  1.    class User extends ActiveRecord
  2.    {
  3.       var $serialize 'preferences';
  4.    }
  5.  
  6.    $User = new User(array('preferences'=>array("background" => "black""display" => 'large')));
  7.    $User->find($user_id);
  8.    $User->preferences // array("background" => "black", "display" => 'large')

== Single table inheritance ==

Active Record allows inheritance by storing the name of the class in a column that by default is called "type" (can be changed by overwriting <tt>AkActiveRecord->_inheritanceColumn</tt>). This means that an inheritance looking like this:

  1.    class Company extends ActiveRecord{}
  2.    class Firm extends Company{}
  3.    class Client extends Company{}
  4.    class PriorityClient extends Client{}

When you do $Firm->create('name =>', "akelos"), this record will be saved in the companies table with type = "Firm". You can then fetch this row again using $Company->find('first', "name = '37signals'") and it will return a Firm object.

If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.

Note, all the attributes for all the cases are kept in the same table. Read more: http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html

== Connection to multiple databases in different models ==

Connections are usually created through AkActiveRecord->establishConnection and retrieved by AkActiveRecord->connection. All classes inheriting from AkActiveRecord will use this connection. But you can also set a class-specific connection. For example, if $Course is a AkActiveRecord, but resides in a different database you can just say $Course->establishConnection and $Course and all its subclasses will use this connection instead.

Active Records will automatically record creation and/or update timestamps of database objects if fields of the names created_at/created_on or updated_at/updated_on are present. Date only: created_on, updated_on Date and time: created_at, updated_at

This behavior can be turned off by setting <tt>$this->_recordTimestamps = false</tt>.



Class Variables

Summary:

Class Constants

Summary:

Method Detail

Summary:
AkActiveRecord __construct ()
void __destruct ()
void actsAs ( $behaviour, [ $options = array()])
void actsLike ()
void addCombinedAttributeConfiguration ( $attribute)
void addConditions ( &$sql, [ $conditions = null], [ $table_alias = null])
void addError ( $attribute, [ $message = 'invalid'])
void addErrorOnBlank ( $attribute_names, [ $message = 'blank'])
void addErrorOnBoundaryBreaking ( $attribute_names,  $range_begin,  $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])
void addErrorOnBoundryBreaking ( $attributes,  $range_begin,  $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])
void addErrorOnEmpty ( $attribute_names, [ $message = 'empty'])
void addErrorToBase ( $message)
void &addObserver ( &$observer)
void afterCreate ()
void afterDestroy ()
void afterSave ()
void afterUpdate ()
void afterValidation ()
void average ( $column_name, [ $options = array()])
void beforeCreate ()
void beforeDestroy ()
void beforeSave ()
void beforeUpdate ()
void calculate ( $operation,  $column_name, [ $options = array()])
void castAttributeForDatabase ( $column_name,  $value, [ $add_quotes = true])
void castAttributeFromDatabase ( $column_name,  $value)
void clearErrors ()
void cloneRecord ()
void collect ( &$source_array,  $key_index,  $value_index)
void composeCombinedAttribute ( $combined_attribute)
void constructFinderSql ( $options, [ $select_from_prefix = 'default'])
void count ()
void countBySql ( $sql)
void countErrors ()
void &create ([ $attributes = null])
void createOrUpdate ([ $validate = true])
void dbug ()
void dbugging ([ $trace_this_on_debug_mode = null])
void debug ([ $data = 'active_record_class'], [ $_functions = 0])
void decomposeCombinedAttribute ( $combined_attribute, [ $used_on_combined_fields = false])
void decrementAndSaveAttribute ( $attribute)
void decrementAttribute ( $attribute)
void decrementCounter ( $counter_name,  $id, [ $difference = 1])
void delete ( $id)
void deleteAll ([ $conditions = null])
void descendsFromActiveRecord ( &$object)
void destroy ([ $id = null])
void destroyAll ( $conditions)
void errorsToString ([ $print = false])
void &establishConnection ([ $specification_or_profile = AK_DEFAULT_DATABASE_PROFILE])
void exists ( $id)
void &find ()
void &findAll ()
void &findAllBy ()
void &findBy ()
void &findBySql ( $sql, [ $limit = null], [ $offset = null], [ $bindings = null])
void &findFirst ()
void &findFirstBy ()
void &findLastBy ()
void &findOrCreateBy ()
void freeze ()
void get ([ $attribute = null], [ $inspect_for_callback_child_method = true])
string getAkelosDataType ( &$adodb_column_object)
void getArrayFromAkString ( $string)
void getAttribute ( $attribute, [ $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_GETTERS])
void getAttributeBeforeTypeCast ( $attribute)
void getAttributeByLocale ( $attribute,  $locale)
void getAttributeCaption ( $attribute)
void getAttributeCondition ( $argument)
void getAttributeLocales ( $attribute)
void getAttributes ()
void getAttributesQuoted ( $attributes_array)
void getBaseErrors ()
void getColumnNames ()
void getColumns ([ $force_reload = false])
void getColumnScale ( $column_name)
void getColumnSettings ([ $force_reload = false])
void getColumnsForAttributes ( $attributes)
void getColumnType ( $column_name)
void getCombinedSubattributes ( $attribute)
void getConditions ( $conditions, [ $prefix = ''], [ $model_name = null])
void &getConnection ()
void getDisplayField ()
void getErrors ()
void getErrorsOn ( $attribute)
void getId ()
void &getObservers ()
void getOnlyAvailableAttributes ( $attributes)
void getPrimaryKey ()
void getSanitizedConditionsArray ( $conditions_array)
void getSubclasses ()
void getTableName ([ $modify_for_associations = true])
void getType ()
boolean hasAttribute (string $attribute)
void hasBeenModified ()
boolean hasColumn ( $column, string $name)
void hasErrors ()
void incrementAndSaveAttribute ( $attribute)
void incrementAttribute ( $attribute)
void incrementCounter ( $counter_name,  $id, [ $difference = 1])
void init ([ $attributes = array()])
void initiateAttributeToNull ( $attribute)
void &instantiate ( $record, [ $set_as_new = true])
void isAttributePresent ( $attribute)
void isBlank ([ $value = null])
boolean isCombinedAttribute (string $attribute)
void isConnected ()
void isFrozen ()
void isInvalid ( $attribute)
void isNewRecord ()
void isValid ()
void loadColumnsSettings ([ $force_reload = false])
void maximum ( $column_name, [ $options = array()])
void minimum ( $column_name, [ $options = array()])
void newRecord ( $attributes)
true notifyObservers ([ $method = null])
void &objectCache ()
void parseAkelosArgs ( &$args)
void quotedId ()
void reload ()
void requiredForCombination ( $attribute)
void save ([ $validate = true])
void select ( &$source_array)
void set ( $attribute, [ $value = null], [ $inspect_for_callback_child_method = true], [ $compose_after_set = true])
void setAttribute ( $attribute,  $value, [ $inspect_for_callback_child_method = AK_ACTIVE_RECORD_ENABLE_CALLBACK_SETTERS], [ $compose_after_set = true])
void setAttributeByLocale ( $attribute,  $value,  $locale)
void setAttributeLocales ( $attribute, [ $values = array()])
void setAttributes ( $attributes, [ $override_attribute_protection = false])
void setColumnSettings ( $column_name,  $column_object)
void &setConnection ([ $db_adapter = null])
void setDisplayField ( $attribute_name)
void setId ( $value)
void setInheritanceColumn ( $column_name)
void setObservableState ( $state_message)
void setPrimaryKey ([ $primary_key = 'id'])
void setSerializeAttribute ( $attr_name, [ $class_name = null])
void setTableName ([ $table_name = null], [ $check_for_existence = AK_ACTIVE_RECORD_VALIDATE_TABLE_NAMES], [ $check_mode = false])
void sum ( $column_name, [ $options = array()])
void t ( $string, [ $array = null])
void toggleAttribute ( $attribute)
void toggleAttributeAndSave ( $attribute)
void toJson ()
void toString ([ $print = false])
void toYaml ([array $data = null])
void transactionFail ()
void typeCondition ([ $table_alias = null])
void update ( $id,  $attributes)
void updateAll ( $updates, [ $conditions = null])
void updateAttribute ( $name,  $value, [ $should_validate = true])
void updateAttributes ( $attributes, [ $object = null])
void validate ()
void validatesAcceptanceOf (accept $attribute_names, [ $message = 'accepted'], [ $accept = 1])
void validatesAssociated ( $attribute_names, [ $message = 'invalid'])
void validatesConfirmationOf ( $attribute_names, [ $message = 'confirmation'])
void validatesExclusionOf ( $attribute_names,  $array_of_possibilities, [ $message = 'exclusion'], [ $allow_null = false])
void validatesFormatOf ( $attribute_names,  $regular_expression, [ $message = 'invalid'], [ $regex_function = 'preg_match'])
void validatesInclusionOf ( $attribute_names,  $array_of_possibilities, [ $message = 'inclusion'], [ $allow_null = false])
void validatesLengthOf ( $attribute_names, [ $options = array()])
void validatesNumericalityOf ( $attribute_names, [ $message = 'not_a_number'], [ $only_integer = false], [ $allow_null = false])
void validatesPresenceOf ( $attribute_names, [ $message = 'blank'])
void validatesSizeOf ( $attribute_names, [ $options = array()])
void validatesUniquenessOf ( $attribute_names, [ $options = array()])
void yieldEachError ()
void yieldError ( $message)
void _destroy ()
void _extractConditionsFromArgs ( $args,  $options)
void _extractOptionsFromArgs ( &$args)
void _extractValueFromDefault ( $default)
void &_findEvery ( $options)
void &_findFromIds ( $ids,  $options)
void &_findInitial ( $options)
void _getFindBySqlAndColumns ( $find_by_sql,  &$query_values)
string _getVariableSqlCondition ( $variable_condition)
void _isOptionsHash ( $options)
void _sanitizeConditionsVariables ( &$options)
void _validateFindOptions ( &$options)

Constructor __construct (line 257)

AkActiveRecord __construct( )

Overrides : AkObject::__construct() Class constructor, overriden in descendant classes

Info

Destructor __destruct (line 313)

void __destruct( )

Overrides : AkObject::__destruct() Class destructor, overriden in descendant classes

Info

Method actsAs (line 4471)

void actsAs( $behaviour, [ $options = array()])

actAs provides a method for extending Active Record models.

Example: $this->actsAs('list', array('scope' => 'todo_list'));

Parameters

  • $behaviour:
  • $options:

Info

Method actsLike (line 4540)

void actsLike( )

Returns a comma separated list of possible acts like (active record, nested set, list)....

Info

Method addCombinedAttributeConfiguration (line 2154)

void addCombinedAttributeConfiguration( $attribute)

Parameters

  • $attribute:

Info

Method addConditions (line 1370)

void addConditions( &$sql, [ $conditions = null], [ $table_alias = null])

Adds a sanitized version of $conditions to the $sql string. Note that the passed $sql string is changed.

Parameters

  • &$sql:
  • $conditions:
  • $table_alias:

Info

Method addError (line 4271)

void addError( $attribute, [ $message = 'invalid'])

Adds an error message ($message) to the ($attribute), which will be returned on a call to <tt>getErrorsOn($attribute)</tt> for the same attribute and ensure that this error object returns false when asked if <tt>hasErrors</tt>. More than one error can be added to the same $attribute in which case an array will be returned on a call to <tt>getErrorsOn($attribute)</tt>.

If no $message is supplied, "invalid" is assumed.

Parameters

  • $attribute:
  • $message:

Info

Method addErrorOnBlank (line 4294)

void addErrorOnBlank( $attribute_names, [ $message = 'blank'])

Will add an error message to each of the attributes in $attributes that is blank (using $this->isBlank).

Parameters

  • $attribute_names:
  • $message:

Info

Method addErrorOnBoundaryBreaking (line 4309)

void addErrorOnBoundaryBreaking( $attribute_names, $range_begin, $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])

Will add an error message to each of the attributes in $attributes that has a length outside of the passed boundary $range.

If the length is above the boundary, the too_long_message message will be used. If below, the too_short_message.

Parameters

  • $attribute_names:
  • $range_begin:
  • $range_end:
  • $too_long_message:
  • $too_short_message:

Info

Method addErrorOnBoundryBreaking (line 4326)

void addErrorOnBoundryBreaking( $attributes, $range_begin, $range_end, [ $too_long_message = 'too_long'], [ $too_short_message = 'too_short'])

Parameters

  • $attributes:
  • $range_begin:
  • $range_end:
  • $too_long_message:
  • $too_short_message:

Info

Method addErrorOnEmpty (line 4280)

void addErrorOnEmpty( $attribute_names, [ $message = 'empty'])

Will add an error message to each of the attributes in $attributes that is empty.

Parameters

  • $attribute_names:
  • $message:

Info

Method addErrorToBase (line 4250)

void addErrorToBase( $message)

Adds an error to the base object instead of any particular attribute. This is used to report errors that doesn't tie to any specific attribute, but rather to the object as a whole. These error messages doesn't get prepended with any field name when iterating with yieldEachFullError, so they should be complete sentences.

Parameters

  • $message:

Info

Method addObserver (line 4203)

void &addObserver( &$observer)

Register the reference to an object object

Parameters

  • &$observer:

Info

Method afterCreate (line 3421)

void afterCreate( )

Info

Method afterDestroy (line 3422)

void afterDestroy( )

Info

Method afterSave (line 3424)

void afterSave( )

Info

Method afterUpdate (line 3417)

void afterUpdate( )

Info

Method afterValidation (line 3418)

void afterValidation( )

Info

Method afterValidationOnCreate (line 3419)

void afterValidationOnCreate( )

Info

Method afterValidationOnUpdate (line 3420)

void afterValidationOnUpdate( )

Info

Method attributesFromColumnDefinition (line 2518)

void attributesFromColumnDefinition( )

Initializes the attributes array with keys matching the columns from the linked table and the values matching the corresponding default value of that column, so that a new instance, or one populated from a passed-in array, still has all the attributes that instances loaded from the database would.

Info

Method average (line 4885)

void average( $column_name, [ $options = array()])

Calculates average value on a given column. The value is returned as a float. See #calculate for examples with options.

$Person->average('age');

Parameters

  • $column_name:
  • $options:

Info

Method beforeCreate (line 3411)

void beforeCreate( )

Callbacks are hooks into the life-cycle of an Active Record object that allows you to trigger logic

before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting beforeDestroy) or to massage attributes before they're validated (by overwriting beforeValidation). As an example of the callbacks initiated, consider the AkActiveRecord->save() call:

  • (-) save()
  • (-) needsValidation()
  • (1) beforeValidation()
  • (2) beforeValidationOnCreate() / beforeValidationOnUpdate()
  • (-) validate()
  • (-) validateOnCreate()
  • (4) afterValidation()
  • (5) afterValidationOnCreate() / afterValidationOnUpdate()
  • (6) beforeSave()
  • (7) beforeCreate() / beforeUpdate()
  • (-) create()
  • (8) afterCreate() / afterUpdate()
  • (9) afterSave()
  • (10) afterDestroy()
  • (11) beforeDestroy()

That's a total of 15 callbacks, which gives you immense power to react and prepare for each state in the Active Record lifecycle.

Examples: class CreditCard extends ActiveRecord { // Strip everything but digits, so the user can specify "555 234 34" or // "5552-3434" or both will mean "55523434" function beforeValidationOnCreate { if(!empty($this->number)){ $this->number = ereg_replace('[^0-9]*','',$this->number); } } }

class Subscription extends ActiveRecord { // Note: This is not implemented yet var $beforeCreate = 'recordSignup';

function recordSignup() { $this->signed_up_on = date("Y-m-d"); } }

class Firm extends ActiveRecord { //Destroys the associated clients and people when the firm is destroyed // Note: This is not implemented yet var $beforeDestroy = array('destroyAssociatedPeople', 'destroyAssociatedClients');

function destroyAssociatedPeople() { $Person = new Person(); $Person->destroyAll("firm_id=>", $this->id); }

function destroyAssociatedClients() { $Client = new Client(); $Client->destroyAll("client_of=>", $this->id); } }

== Canceling callbacks ==

If a before* callback returns false, all the later callbacks and the associated action are cancelled. If an after* callback returns false, all the later callbacks are cancelled. Callbacks are generally run in the order they are defined, with the exception of callbacks defined as methods on the model, which are called last.

Override this methods to hook Active Records

Info

  • access - public

Method beforeDestroy (line 3423)

void beforeDestroy( )

Info

Method beforeSave (line 3415)

void beforeSave( )

Info

Method beforeUpdate (line 3416)

void beforeUpdate( )

Info

Method beforeValidation (line 3412)

void beforeValidation( )

Info

Method beforeValidationOnCreate (line 3413)

void beforeValidationOnCreate( )

Info

Method beforeValidationOnUpdate (line 3414)

void beforeValidationOnUpdate( )

Info

Method calculate (line 4947)

void calculate( $operation, $column_name, [ $options = array()])

This calculates aggregate values in the given column: Methods for count, sum, average, minimum, and maximum have been added as shortcuts.

Options such as 'conditions', 'order', 'group', 'having', and 'joins' can be passed to customize the query.

There are two basic forms of output: * Single aggregate value: The single value is type cast to integer for COUNT, float for AVG, and the given column's type for everything else. * Grouped values: This returns an ordered hash of the values and groups them by the 'group' option. It takes a column name.

$values = $Person->maximum('age', array('group' => 'last_name')); echo $values["Drake"] => 43

Options: * <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array( "user_name = ?", username ). See conditions in the intro. * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). The records will be returned read-only since they will have attributes that do not correspond to the table's columns. * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join. * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...

Examples: $Person->calculate('count', 'all'); // The same as $Person->count(); $Person->average('age'); // SELECT AVG(age) FROM people... $Person->minimum('age', array('conditions' => array('last_name != ?', 'Drake'))); // Selects the minimum age for everyone with a last name other than 'Drake' $Person->minimum('age', array('having' => 'min(age) > 17', 'group' => 'last'_name)); // Selects the minimum age for any family without any minors

Parameters

  • $operation:
  • $column_name:
  • $options:

Info

Method castAttributeForDatabase (line 3151)

void castAttributeForDatabase( $column_name, $value, [ $add_quotes = true])

Parameters

  • $column_name:
  • $value:
  • $add_quotes:

Info

Method castAttributeFromDatabase (line 3215)

void castAttributeFromDatabase( $column_name, $value)

Parameters

  • $column_name:
  • $value:

Info

Method clearErrors (line 4421)

void clearErrors( )

Removes all the errors that have been added.

Info

Method cloneRecord (line 343)

void cloneRecord( )

Returns a clone of the record that hasn't been assigned an id yet and is treated as a new record.

Info

Method collect (line 4729)

void collect( &$source_array, $key_index, $value_index)

Collect is a function for selecting items from double depth array like the ones returned by the AkActiveRecord. This comes useful when you just need some fields for generating tables, select lists with only desired fields.

$people_for_select = Ak::select($People->find(),'id','email');

Returns something like: array ( array ('10' => 'jose@example.com'), array ('15' => 'alicia@example.com'), array ('16' => 'hilario@example.com'), array ('18' => 'bermi@example.com') );

Parameters

  • &$source_array:
  • $key_index:
  • $value_index:

Info

Method composeCombinedAttribute (line 2185)

void composeCombinedAttribute( $combined_attribute)

Parameters

  • $combined_attribute:

Info

Method composeCombinedAttributes (line 2174)

void composeCombinedAttributes( )

Info

Method constructFinderSql (line 1347)

void constructFinderSql( $options, [ $select_from_prefix = 'default'])

Parameters

  • $options:
  • $select_from_prefix:

Info

Method count (line 4873)

void count( )

Count operates using three different approaches.

* Count all: By not passing any parameters to count, it will return a count of all the rows for the model. * Count by conditions or joins * Count using options will find the row count matched by the options used.

The last approach, count using options, accepts an option hash as the only parameter. The options are:

* <tt>'conditions'</tt>: An SQL fragment like "administrator = 1" or array("user_name = ?", $username ). See conditions in the intro. * <tt>'joins'</tt>: An SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id". (Rarely needed). * <tt>'order'</tt>: An SQL fragment like "created_at DESC, name" (really only used with GROUP BY calculations). * <tt>'group'</tt>: An attribute name by which the result should be grouped. Uses the GROUP BY SQL-clause. * <tt>'select'</tt>: By default, this is * as in SELECT * FROM, but can be changed if you for example want to do a join. * <tt>'distinct'</tt>: Set this to true to make this a distinct calculation, such as SELECT COUNT(DISTINCT posts.id) ...

Examples for counting all: $Person->count(); // returns the total count of all people

Examples for count by +conditions+ and +joins+ (this has been deprecated): $Person->count("age > 26"); // returns the number of people older than 26 $Person->find("age > 26 AND job.salary > 60000", "LEFT JOIN jobs on jobs.person_id = ".$Person->id); // returns the total number of rows matching the conditions and joins fetched by SELECT COUNT(*).

Examples for count with options: $Person->count('conditions' => "age > 26"); $Person->count('conditions' => "age > 26 AND job.salary > 60000", 'joins' => "LEFT JOIN jobs on jobs.person_id = $Person->id"); // finds the number of rows matching the conditions and joins. $Person->count('id', 'conditions' => "age > 26"); // Performs a COUNT(id) $Person->count('all', 'conditions' => "age > 26"); // Performs a COUNT(*) ('all' is an alias for '*')

Note: $Person->count('all') will not work because it will use 'all' as the condition. Use $Person->count() instead.

Info

Method countBySql (line 578)

void countBySql( $sql)

Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part.

$Product->countBySql("SELECT COUNT(*) FROM sales s, customers c WHERE s.customer_id = c.id");

Parameters

  • $sql:

Info

Method countErrors (line 4430)

void countErrors( )

Returns the total number of errors added. Two errors added to the same attribute will be counted as such with this as well.

Info

Method create (line 393)

void &create( [ $attributes = null])

Overrides : AkAssociatedActiveRecord::create() parent method not documented

Creates an object, instantly saves it as a record (if the validation permits it), and returns it.

If the save fail under validations, the unsaved object is still returned.

Parameters

  • $attributes:

Info

Method createOrUpdate (line 410)

void createOrUpdate( [ $validate = true])

Parameters

  • $validate:

Info

Method dbug (line 4559)

void dbug( )

Info

Method dbugging (line 4599)

void dbugging( [ $trace_this_on_debug_mode = null])

Parameters

  • $trace_this_on_debug_mode:

Info

Method debug (line 4610)

void debug( [ $data = 'active_record_class'], [ $_functions = 0])

Parameters

  • $data:
  • $_functions:

Info

Method decomposeCombinedAttribute (line 2260)

void decomposeCombinedAttribute( $combined_attribute, [ $used_on_combined_fields = false])

Parameters

  • $combined_attribute:
  • $used_on_combined_fields:

Info

Method decomposeCombinedAttributes (line 2250)

void decomposeCombinedAttributes( )

Info

Method decrementAndSaveAttribute (line 1854)

void decrementAndSaveAttribute( $attribute)

Decrements the attribute and saves the record.

Parameters

  • $attribute:

Info

Method decrementAttribute (line 1843)

void decrementAttribute( $attribute)

Initializes the attribute to zero if null and subtracts one. Only makes sense for number-based attributes. Returns attribute value.

Parameters

  • $attribute:

Info

Method decrementCounter (line 1835)

void decrementCounter( $counter_name, $id, [ $difference = 1])

Works like AkActiveRecord::incrementCounter, but decrements instead.

Parameters

  • $counter_name:
  • $id:
  • $difference:

Info

Method delete (line 723)

void delete( $id)

Deletes the record with the given id without instantiating an object first. If an array of ids is provided, all of them are deleted.

Parameters

  • $id:

Info

Method deleteAll (line 742)

void deleteAll( [ $conditions = null])

Deletes all the records that matches the condition without instantiating the objects first (and hence not calling the destroy method). Example:

  1. $Post->destroyAll("person_id = 5 AND (category = 'Something' OR category = 'Else')");

Important note: Conditions are not sanitized yet so beware of accepting variable conditions when using this function

Parameters

  • $conditions:

Info

Method descendsFromActiveRecord (line 1522)

void descendsFromActiveRecord( &$object)

Parameters

  • &$object:

Info