class Model (View source)

The base class for your models.

Defining an ActiveRecord model for a table called people and orders:

CREATE TABLE people( id int primary key auto_increment, parent_id int, first_name varchar(50), last_name varchar(50) );

CREATE TABLE orders( id int primary key auto_increment, person_id int not null, cost decimal(10,2), total decimal(10,2) );

class Person extends ActiveRecord\Model { static $belongs_to = array( array('parent', 'foreign_key' => 'parent_id', 'class_name' => 'Person') );

static $has_many = array( array('children', 'foreign_key' => 'parent_id', 'class_name' => 'Person'), array('orders') );

static $validates_length_of = array( array('first_name', 'within' => array(1,50)), array('last_name', 'within' => array(1,50)) ); }

class Order extends ActiveRecord\Model { static $belongs_to = array( array('person') );

static $validates_numericality_of = array( array('cost', 'greater_than' => 0), array('total', 'greater_than' => 0) );

static $before_save = array('calculate_total_with_tax');

public function calculate_total_with_tax() { $this->total = $this->cost * 0.045; } }

For a more in-depth look at defining models, relationships, callbacks and many other things please consult our {@link http://www.phpactiverecord.org/guides Guides}.

Properties

Errors $errors An instance of {@link Errors} and will be instantiated once a write method is called.
static string $connection Set to the name of the connection this {@link Model} should use.
static string $db Set to the name of the database this Model's table is in.
static string $table_name Set this to explicitly specify the model's table name if different from inferred name.
static string $primary_key Set this to override the default primary key name if different from default name of "id".
static string $sequence Set this to explicitly specify the sequence name for the table.
static $cache Set this to true in your subclass to use caching for this model.
static integer $cache_expire Set this to specify an expiration period for this model.
static array $alias_attribute Allows you to create aliases for attributes.
static array $attr_accessible Whitelist of attributes that are checked from mass-assignment calls such as constructing a model or using update_attributes.
static array $attr_protected Blacklist of attributes that cannot be mass-assigned.
static array $delegate Delegates calls to a relationship.
static array $VALID_OPTIONS A list of valid finder options.

Methods

__construct(array $attributes = array(), boolean $guard_attributes = true, boolean $instantiating_via_find = false, boolean $new_record = true)

Constructs a model.

mixed
__get(string $name)

Magic method which delegates to read_attribute(). This handles firing off getter methods, as they are not checked/invoked inside of read_attribute(). This circumvents the problem with a getter being accessed with the same name as an actual attribute.

boolean
__isset(string $attribute_name)

Determines if an attribute exists for this {@link Model}.

mixed
__set(string $name, mixed $value)

Magic allows un-defined attributes to set via $attributes.

__wakeup()

No description

mixed
assign_attribute(string $name, mixed $value)

Assign a value to an attribute.

mixed
read_attribute(string $name)

Retrieves an attribute's value or a relationship object based on the name passed. If the attribute accessed is 'id' then it will return the model's primary key no matter what the actual attribute name is for the primary key.

flag_dirty(string $name)

Flags an attribute as dirty.

mixed
dirty_attributes()

Returns hash of attributes that have been modified since loading the model.

boolean
attribute_is_dirty(string $attribute)

Check if a particular attribute has been modified since loading the model.

array
attributes()

Returns a copy of the model's attributes hash.

string
get_primary_key(boolean $first = false)

Retrieve the primary key name.

string
get_real_attribute_name(string $name)

Returns the actual attribute name if $name is aliased.

array
get_validation_rules()

Returns array of validator data for this Model.

array
get_values_for(array $attributes)

Returns an associative array containing values for all the attributes in $attributes

static string
table_name()

Retrieves the name of the table for this Model.

boolean
is_readonly()

Determine if the model is in read-only mode.

boolean
is_new_record()

Determine if the model is a new record.

readonly(boolean $readonly = true)

Flag model as readonly.

static Connection
connection()

Retrieve the connection for this model.

static Connection
reestablish_connection()

Re-establishes the database connection with a new connection.

static Table
table()

Returns the {@link Table} object for this model.

static Model
create(array $attributes, boolean $validate = true, boolean $guard_attributes = true)

Creates a model and saves it to the database.

boolean
save(boolean $validate = true)

Save the model to the database.

expire_cache()

No description

cache_key()

No description

static 
delete_all($options = array())

Deletes records matching conditions in $options

static 
update_all($options = array())

Updates records using set in $options

boolean
delete()

Deletes this model from the database and returns true if successful.

array
values_for_pk()

Helper that creates an array of values for the primary key(s).

array
values_for(array $attribute_names)

Helper to return a hash of values for the specified attributes.

boolean
is_dirty()

Returns true if the model has been modified.

boolean
is_valid()

Run validations on model and returns whether or not model passed validation.

boolean
is_invalid()

Runs validations and returns true if invalid.

set_timestamps()

Updates a model's timestamps.

boolean
update_attributes(array $attributes)

Mass update the model with an array of attribute data and saves to the database.

boolean
update_attribute(string $name, mixed $value)

Updates a single attribute and saves the record without going through the normal validation procedure.

set_attributes(array $attributes)

Mass update the model with data from an attributes hash.

void
set_relationship_from_eager_load(Model $model = null, $name)

Add a model to the given named ($name) relationship.

reload()

Reloads the attributes and relationships of this object from the database.

__clone()

No description

reset_dirty()

Resets the dirty array.

static Model
__callStatic(string $method, mixed $args)

Enables the use of dynamic finders.

mixed
__call(string $method, mixed $args)

Enables the use of build|create for associations.

static array
all()

Alias for self::find('all').

static int
count()

Get a count of qualifying records.

static boolean
exists()

Determine if a record exists.

static Model
first()

Alias for self::find('first').

static Model
last()

Alias for self::find('last')

static mixed
find()

Find records in the database.

static array
get_models_from_cache($pks, $options)

Will look up a list of primary keys from cache

static Model
find_by_pk(array $values, array $options)

Finder method which will find by a single or array of primary keys for this model.

static array
find_by_sql(string $sql, array $values = null)

Find using a raw SELECT query.

static object
query(string $sql, array $values = null)

Helper method to run arbitrary queries against the model's database connection.

static boolean
is_options_hash(array $array, bool $throw = true)

Determines if the specified array is a valid ActiveRecord options array.

static array
pk_conditions(mixed $args)

Returns a hash containing the names => values of the primary key.

static array
extract_and_validate_options(array $array)

Pulls out the options hash from $array if any.

string
to_json(array $options = array())

Returns a JSON representation of this model.

string
to_xml(array $options = array())

Returns an XML representation of this model.

string
to_csv(array $options = array())

Returns an CSV representation of this model.

array
to_array(array $options = array())

Returns an Array representation of this model.

static boolean
transaction(callable $closure)

Executes a block of code inside a database transaction.

Details

Model __construct(array $attributes = array(), boolean $guard_attributes = true, boolean $instantiating_via_find = false, boolean $new_record = true)

Constructs a model.

When a user instantiates a new object (e.g.: it was not ActiveRecord that instantiated via a find) then @var $attributes will be mapped according to the schema's defaults. Otherwise, the given $attributes will be mapped via set_attributes_via_mass_assignment.

new Person(array('first_name' => 'Tito', 'last_name' => 'the Grief'));

Parameters

array $attributes Hash containing names and values to mass assign to the model
boolean $guard_attributes Set to true to guard protected/non-accessible attributes
boolean $instantiating_via_find Set to true if this model is being created from a find call
boolean $new_record Set to true if this should be considered a new record

Return Value

Model

mixed __get(string $name)

Magic method which delegates to read_attribute(). This handles firing off getter methods, as they are not checked/invoked inside of read_attribute(). This circumvents the problem with a getter being accessed with the same name as an actual attribute.

You can also define customer getter methods for the model.

EXAMPLE: class User extends ActiveRecord\Model {

# define custom getter methods. Note you must # prepend get_ to your method name: function get_middle_initial() { return $this->middle_name{0}; } }

$user = new User(); echo $user->middle_name; # will call $user->get_middle_name()

If you define a custom getter with the same name as an attribute then you will need to use read_attribute() to get the attribute's value. This is necessary due to the way __get() works.

For example, assume 'name' is a field on the table and we're defining a custom getter for 'name':

class User extends ActiveRecord\Model {

# INCORRECT way to do it # function get_name() { # return strtoupper($this->name); # }

function get_name() { return strtoupper($this->read_attribute('name')); } }

$user = new User(); $user->name = 'bob'; echo $user->name; # => BOB

Parameters

string $name Name of an attribute

Return Value

mixed The value of the attribute

See also

read_attribute()

boolean __isset(string $attribute_name)

Determines if an attribute exists for this {@link Model}.

Parameters

string $attribute_name

Return Value

boolean

mixed __set(string $name, mixed $value)

Magic allows un-defined attributes to set via $attributes.

You can also define customer setter methods for the model.

EXAMPLE: class User extends ActiveRecord\Model {

# define custom setter methods. Note you must # prepend set_ to your method name: function set_password($plaintext) { $this->encrypted_password = md5($plaintext); } }

$user = new User(); $user->password = 'plaintext'; # will call $user->set_password('plaintext')

If you define a custom setter with the same name as an attribute then you will need to use assign_attribute() to assign the value to the attribute. This is necessary due to the way __set() works.

For example, assume 'name' is a field on the table and we're defining a custom setter for 'name':

class User extends ActiveRecord\Model {

# INCORRECT way to do it # function set_name($name) { # $this->name = strtoupper($name); # }

function set_name($name) { $this->assign_attribute('name',strtoupper($name)); } }

$user = new User(); $user->name = 'bob'; echo $user->name; # => BOB

Parameters

string $name Name of attribute, relationship or other to set
mixed $value The value

Return Value

mixed The value

Exceptions

{@link UndefinedPropertyException} if $name does not exist

__wakeup()

mixed assign_attribute(string $name, mixed $value)

Assign a value to an attribute.

Parameters

string $name Name of the attribute
mixed $value &$value Value of the attribute

Return Value

mixed the attribute value

mixed read_attribute(string $name)

Retrieves an attribute's value or a relationship object based on the name passed. If the attribute accessed is 'id' then it will return the model's primary key no matter what the actual attribute name is for the primary key.

Parameters

string $name Name of an attribute

Return Value

mixed The value of the attribute

Exceptions

{@link UndefinedPropertyException} if name could not be resolved to an attribute, relationship, ...

flag_dirty(string $name)

Flags an attribute as dirty.

Parameters

string $name Attribute name

mixed dirty_attributes()

Returns hash of attributes that have been modified since loading the model.

Return Value

mixed null if no dirty attributes otherwise returns array of dirty attributes.

boolean attribute_is_dirty(string $attribute)

Check if a particular attribute has been modified since loading the model.

Parameters

string $attribute Name of the attribute

Return Value

boolean TRUE if it has been modified.

array attributes()

Returns a copy of the model's attributes hash.

Return Value

array A copy of the model's attribute data

string get_primary_key(boolean $first = false)

Retrieve the primary key name.

Parameters

boolean $first Set to true to return the first value in the pk array only

Return Value

string The primary key for the model

string get_real_attribute_name(string $name)

Returns the actual attribute name if $name is aliased.

Parameters

string $name An attribute name

Return Value

string

array get_validation_rules()

Returns array of validator data for this Model.

Will return an array looking like:

array( 'name' => array( array('validator' => 'validates_presence_of'), array('validator' => 'validates_inclusion_of', 'in' => array('Bob','Joe','John')), 'password' => array( array('validator' => 'validates_length_of', 'minimum' => 6)) ) );

Return Value

array An array containing validator data for this model.

array get_values_for(array $attributes)

Returns an associative array containing values for all the attributes in $attributes

Parameters

array $attributes Array containing attribute names

Return Value

array A hash containing $name => $value

static string table_name()

Retrieves the name of the table for this Model.

Return Value

string

boolean is_readonly()

Determine if the model is in read-only mode.

Return Value

boolean

boolean is_new_record()

Determine if the model is a new record.

Return Value

boolean

readonly(boolean $readonly = true)

Flag model as readonly.

Parameters

boolean $readonly Set to true to put the model into readonly mode

static Connection connection()

Retrieve the connection for this model.

Return Value

Connection

static Connection reestablish_connection()

Re-establishes the database connection with a new connection.

Return Value

Connection

static Table table()

Returns the {@link Table} object for this model.

Be sure to call in static scoping: static::table()

Return Value

Table

static Model create(array $attributes, boolean $validate = true, boolean $guard_attributes = true)

Creates a model and saves it to the database.

Parameters

array $attributes Array of the models attributes
boolean $validate True if the validators should be run
boolean $guard_attributes Set to true to guard protected/non-accessible attributes

Return Value

Model

boolean save(boolean $validate = true)

Save the model to the database.

This function will automatically determine if an INSERT or UPDATE needs to occur. If a validation or a callback for this model returns false, then the model will not be saved and this will return false.

If saving an existing model only data that has changed will be saved.

Parameters

boolean $validate Set to true or false depending on if you want the validators to run or not

Return Value

boolean True if the model was saved to the database otherwise false

protected expire_cache()

protected cache_key()

static delete_all($options = array())

Deletes records matching conditions in $options

Does not instantiate models and therefore does not invoke callbacks

Delete all using a hash:

YourModel::delete_all(array('conditions' => array('name' => 'Tito')));

Delete all using an array:

YourModel::delete_all(array('conditions' => array('name = ?', 'Tito')));

Delete all using a string:

YourModel::delete_all(array('conditions' => 'name = "Tito"'));

An options array takes the following parameters:

  • conditions: Conditions using a string/hash/array
  • limit: Limit number of records to delete (MySQL & Sqlite only)
  • order: A SQL fragment for ordering such as: 'name asc', 'id desc, name asc' (MySQL & Sqlite only)

Parameters

$options

static update_all($options = array())

Updates records using set in $options

Does not instantiate models and therefore does not invoke callbacks

Update all using a hash:

YourModel::update_all(array('set' => array('name' => "Bob")));

Update all using a string:

YourModel::update_all(array('set' => 'name = "Bob"'));

An options array takes the following parameters:

  • set: String/hash of field names and their values to be updated with
  • conditions: Conditions using a string/hash/array
  • limit: Limit number of records to update (MySQL & Sqlite only)
  • order: A SQL fragment for ordering such as: 'name asc', 'id desc, name asc' (MySQL & Sqlite only)

Parameters

$options

boolean delete()

Deletes this model from the database and returns true if successful.

Return Value

boolean

array values_for_pk()

Helper that creates an array of values for the primary key(s).

Return Value

array An array in the form array(key_name => value, ...)

array values_for(array $attribute_names)

Helper to return a hash of values for the specified attributes.

Parameters

array $attribute_names Array of attribute names

Return Value

array An array in the form array(name => value, ...)

boolean is_dirty()

Returns true if the model has been modified.

Return Value

boolean true if modified

boolean is_valid()

Run validations on model and returns whether or not model passed validation.

Return Value

boolean

See also

is_invalid

boolean is_invalid()

Runs validations and returns true if invalid.

Return Value

boolean

See also

is_valid

set_timestamps()

Updates a model's timestamps.

boolean update_attributes(array $attributes)

Mass update the model with an array of attribute data and saves to the database.

Parameters

array $attributes An attribute data array in the form array(name => value, ...)

Return Value

boolean True if successfully updated and saved otherwise false

boolean update_attribute(string $name, mixed $value)

Updates a single attribute and saves the record without going through the normal validation procedure.

Parameters

string $name Name of attribute
mixed $value Value of the attribute

Return Value

boolean True if successful otherwise false

set_attributes(array $attributes)

Mass update the model with data from an attributes hash.

Unlike update_attributes() this method only updates the model's data but DOES NOT save it to the database.

Parameters

array $attributes An array containing data to update in the form array(name => value, ...)

See also

update_attributes

void set_relationship_from_eager_load(Model $model = null, $name)

Add a model to the given named ($name) relationship.

Parameters

Model $model
$name of relationship for this table

Return Value

void

Model reload()

Reloads the attributes and relationships of this object from the database.

Return Value

Model

__clone()

reset_dirty()

Resets the dirty array.

See also

dirty_attributes

static Model __callStatic(string $method, mixed $args)

Enables the use of dynamic finders.

Dynamic finders are just an easy way to do queries quickly without having to specify an options array with conditions in it.

SomeModel::find_by_first_name('Tito'); SomeModel::find_by_first_name_and_last_name('Tito','the Grief'); SomeModel::find_by_first_name_or_last_name('Tito','the Grief'); SomeModel::find_all_by_last_name('Smith'); SomeModel::count_by_name('Bob') SomeModel::count_by_name_or_state('Bob','VA') SomeModel::count_by_name_and_state('Bob','VA')

You can also create the model if the find call returned no results:

Person::find_or_create_by_name('Tito');

would be the equivalent of

if (!Person::find_by_name('Tito')) Person::create(array('Tito'));

Some other examples of find_or_create_by:

Person::find_or_create_by_name_and_id('Tito',1); Person::find_or_create_by_name_and_id(array('name' => 'Tito', 'id' => 1));

Parameters

string $method Name of method
mixed $args Method args

Return Value

Model

Exceptions

{@link ActiveRecordException} if invalid query

See also

find

mixed __call(string $method, mixed $args)

Enables the use of build|create for associations.

Parameters

string $method Name of method
mixed $args Method args

Return Value

mixed An instance of a given {@link AbstractRelationship}

static array all()

Alias for self::find('all').

Return Value

array array of records found

See also

find

static int count()

Get a count of qualifying records.

YourModel::count(array('conditions' => 'amount > 3.14159265'));

Return Value

int Number of records that matched the query

See also

find

static boolean exists()

Determine if a record exists.

SomeModel::exists(123); SomeModel::exists(array('conditions' => array('id=? and name=?', 123, 'Tito'))); SomeModel::exists(array('id' => 123, 'name' => 'Tito'));

Return Value

boolean

See also

find

static Model first()

Alias for self::find('first').

Return Value

Model The first matched record or null if not found

See also

find

static Model last()

Alias for self::find('last')

Return Value

Model The last matched record or null if not found

See also

find

static mixed find()

Find records in the database.

Finding by the primary key:

queries for the model with id=123

YourModel::find(123);

queries for model with id in(1,2,3)

YourModel::find(1,2,3);

finding by pk accepts an options array

YourModel::find(123,array('order' => 'name desc'));

Finding by using a conditions array:

YourModel::find('first', array('conditions' => array('name=?','Tito'), 'order' => 'name asc')) YourModel::find('all', array('conditions' => 'amount > 3.14159265')); YourModel::find('all', array('conditions' => array('id in(?)', array(1,2,3))));

Finding by using a hash:

YourModel::find(array('name' => 'Tito', 'id' => 1)); YourModel::find('first',array('name' => 'Tito', 'id' => 1)); YourModel::find('all',array('name' => 'Tito', 'id' => 1));

An options array can take the following parameters:

  • select: A SQL fragment for what fields to return such as: '*', 'people.*', 'first_name, last_name, id'
  • joins: A SQL join fragment such as: 'JOIN roles ON(roles.user_id=user.id)' or a named association on the model
  • include: TODO not implemented yet
  • conditions: A SQL fragment such as: 'id=1', array('id=1'), array('name=? and id=?','Tito',1), array('name IN(?)', array('Tito','Bob')), array('name' => 'Tito', 'id' => 1)
  • limit: Number of records to limit the query to
  • offset: The row offset to return results from for the query
  • order: A SQL fragment for order such as: 'name asc', 'name asc, id desc'
  • readonly: Return all the models in readonly mode
  • group: A SQL group by fragment

Return Value

mixed An array of records found if doing a find_all otherwise a single Model object or null if it wasn't found. NULL is only return when doing a first/last find. If doing an all find and no records matched this will return an empty array.

Exceptions

{@link RecordNotFound} if no options are passed or finding by pk and no records matched

static protected array get_models_from_cache($pks, $options)

Will look up a list of primary keys from cache

Parameters

$pks
$options

Return Value

array

static Model find_by_pk(array $values, array $options)

Finder method which will find by a single or array of primary keys for this model.

Parameters

array $values An array containing values for the pk
array $options An options array

Return Value

Model

Exceptions

{@link RecordNotFound} if a record could not be found

See also

find

static array find_by_sql(string $sql, array $values = null)

Find using a raw SELECT query.

YourModel::find_by_sql("SELECT * FROM people WHERE name=?",array('Tito')); YourModel::find_by_sql("SELECT * FROM people WHERE name='Tito'");

Parameters

string $sql The raw SELECT query
array $values An array of values for any parameters that needs to be bound

Return Value

array An array of models

static object query(string $sql, array $values = null)

Helper method to run arbitrary queries against the model's database connection.

Parameters

string $sql SQL to execute
array $values Bind values, if any, for the query

Return Value

object A PDOStatement object

static boolean is_options_hash(array $array, bool $throw = true)

Determines if the specified array is a valid ActiveRecord options array.

Parameters

array $array An options array
bool $throw True to throw an exception if not valid

Return Value

boolean True if valid otherwise valse

Exceptions

{@link ActiveRecordException} if the array contained any invalid options

static array pk_conditions(mixed $args)

Returns a hash containing the names => values of the primary key.

Parameters

mixed $args Primary key value(s)

Return Value

array An array in the form array(name => value, ...)

static array extract_and_validate_options(array $array)

Pulls out the options hash from $array if any.

Parameters

array $array &$array An array

Return Value

array A valid options array

string to_json(array $options = array())

Returns a JSON representation of this model.

Parameters

array $options An array containing options for json serialization (see {@link Serialization} for valid options)

Return Value

string JSON representation of the model

See also

Serialization

string to_xml(array $options = array())

Returns an XML representation of this model.

Parameters

array $options An array containing options for xml serialization (see {@link Serialization} for valid options)

Return Value

string XML representation of the model

See also

Serialization

string to_csv(array $options = array())

Returns an CSV representation of this model.

Can take optional delimiter and enclosure (defaults are , and double quotes)

Ex: ActiveRecord\CsvSerializer::$delimiter=';'; ActiveRecord\CsvSerializer::$enclosure=''; YourModel::find('first')->to_csv(array('only'=>array('name','level'))); returns: Joe,2

YourModel::find('first')->to_csv(array('only_header'=>true,'only'=>array('name','level'))); returns: name,level

Parameters

array $options An array containing options for csv serialization (see {@link Serialization} for valid options)

Return Value

string CSV representation of the model

See also

Serialization

array to_array(array $options = array())

Returns an Array representation of this model.

Parameters

array $options An array containing options for json serialization (see {@link Serialization} for valid options)

Return Value

array Array representation of the model

See also

Serialization

static boolean transaction(callable $closure)

Executes a block of code inside a database transaction.

YourModel::transaction(function() { YourModel::create(array("name" => "blah")); });

If an exception is thrown inside the closure the transaction will automatically be rolled back. You can also return false from your closure to cause a rollback:

YourModel::transaction(function() { YourModel::create(array("name" => "blah")); throw new Exception("rollback!"); });

YourModel::transaction(function() { YourModel::create(array("name" => "blah")); return false; # rollback! });

Parameters

callable $closure The closure to execute. To cause a rollback have your closure return false or throw an exception.

Return Value

boolean True if the transaction was committed, False if rolled back.