Model
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
Constructs a model.
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.
Determines if an attribute exists for this {@link Model}.
Magic allows un-defined attributes to set via $attributes.
No description
Assign a value to an attribute.
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.
Flags an attribute as dirty.
Returns hash of attributes that have been modified since loading the model.
Check if a particular attribute has been modified since loading the model.
Returns a copy of the model's attributes hash.
Retrieve the primary key name.
Returns the actual attribute name if $name is aliased.
Returns array of validator data for this Model.
Returns an associative array containing values for all the attributes in $attributes
Retrieves the name of the table for this Model.
Determine if the model is in read-only mode.
Determine if the model is a new record.
Flag model as readonly.
Retrieve the connection for this model.
Re-establishes the database connection with a new connection.
Creates a model and saves it to the database.
Save the model to the database.
No description
No description
Deletes records matching conditions in $options
Updates records using set in $options
Deletes this model from the database and returns true if successful.
Helper that creates an array of values for the primary key(s).
Helper to return a hash of values for the specified attributes.
Returns true if the model has been modified.
Run validations on model and returns whether or not model passed validation.
Runs validations and returns true if invalid.
Updates a model's timestamps.
Mass update the model with an array of attribute data and saves to the database.
Updates a single attribute and saves the record without going through the normal validation procedure.
Mass update the model with data from an attributes hash.
Add a model to the given named ($name) relationship.
No description
Resets the dirty array.
Enables the use of dynamic finders.
Enables the use of build|create for associations.
Alias for self::find('all').
Get a count of qualifying records.
Determine if a record exists.
Find records in the database.
Will look up a list of primary keys from cache
Finder method which will find by a single or array of primary keys for this model.
Find using a raw SELECT query.
Helper method to run arbitrary queries against the model's database connection.
Determines if the specified array is a valid ActiveRecord options array.
Returns a hash containing the names => values of the primary key.
Pulls out the options hash from $array if any.
Returns a JSON representation of this model.
Returns an XML representation of this model.
Returns an CSV representation of this model.
Returns an Array representation of this model.
Executes a block of code inside a database transaction.
Details
at line 264
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'));
at line 337
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
at line 356
boolean
__isset(string $attribute_name)
Determines if an attribute exists for this {@link Model}.
at line 411
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
at line 437
__wakeup()
at line 450
mixed
assign_attribute(string $name, mixed $value)
Assign a value to an attribute.
at line 494
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.
at line 550
flag_dirty(string $name)
Flags an attribute as dirty.
at line 563
mixed
dirty_attributes()
Returns hash of attributes that have been modified since loading the model.
at line 577
boolean
attribute_is_dirty(string $attribute)
Check if a particular attribute has been modified since loading the model.
at line 587
array
attributes()
Returns a copy of the model's attributes hash.
at line 598
string
get_primary_key(boolean $first = false)
Retrieve the primary key name.
at line 610
string
get_real_attribute_name(string $name)
Returns the actual attribute name if $name is aliased.
at line 639
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))
)
);
at line 653
array
get_values_for(array $attributes)
Returns an associative array containing values for all the attributes in $attributes
at line 670
static string
table_name()
Retrieves the name of the table for this Model.
at line 699
boolean
is_readonly()
Determine if the model is in read-only mode.
at line 709
boolean
is_new_record()
Determine if the model is a new record.
at line 731
readonly(boolean $readonly = true)
Flag model as readonly.
at line 741
static Connection
connection()
Retrieve the connection for this model.
at line 751
static Connection
reestablish_connection()
Re-establishes the database connection with a new connection.
at line 763
static Table
table()
Returns the {@link Table} object for this model.
Be sure to call in static scoping: static::table()
at line 776
static Model
create(array $attributes, boolean $validate = true, boolean $guard_attributes = true)
Creates a model and saves it to the database.
at line 796
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.
at line 895
protected
expire_cache()
at line 904
protected
cache_key()
at line 944
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)
at line 997
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)
at line 1030
boolean
delete()
Deletes this model from the database and returns true if successful.
at line 1054
array
values_for_pk()
Helper that creates an array of values for the primary key(s).
at line 1065
array
values_for(array $attribute_names)
Helper to return a hash of values for the specified attributes.
at line 1111
boolean
is_dirty()
Returns true if the model has been modified.
at line 1122
boolean
is_valid()
Run validations on model and returns whether or not model passed validation.
at line 1133
boolean
is_invalid()
Runs validations and returns true if invalid.
at line 1141
set_timestamps()
Updates a model's timestamps.
at line 1158
boolean
update_attributes(array $attributes)
Mass update the model with an array of attribute data and saves to the database.
at line 1171
boolean
update_attribute(string $name, mixed $value)
Updates a single attribute and saves the record without going through the normal validation procedure.
at line 1186
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.
at line 1254
void
set_relationship_from_eager_load(Model $model = null, $name)
Add a model to the given named ($name) relationship.
at line 1280
Model
reload()
Reloads the attributes and relationships of this object from the database.
at line 1292
__clone()
at line 1304
reset_dirty()
Resets the dirty array.
at line 1355
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));
at line 1403
mixed
__call(string $method, mixed $args)
Enables the use of build|create for associations.
at line 1434
static array
all()
Alias for self::find('all').
at line 1449
static int
count()
Get a count of qualifying records.
YourModel::count(array('conditions' => 'amount > 3.14159265'));
at line 1481
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'));
at line 1562
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
at line 1619
static protected array
get_models_from_cache($pks, $options)
Will look up a list of primary keys from cache
at line 1650
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.
at line 1698
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'");
at line 1710
static object
query(string $sql, array $values = null)
Helper method to run arbitrary queries against the model's database connection.
at line 1723
static boolean
is_options_hash(array $array, bool $throw = true)
Determines if the specified array is a valid ActiveRecord options array.
at line 1748
static array
pk_conditions(mixed $args)
Returns a hash containing the names => values of the primary key.
at line 1762
static array
extract_and_validate_options(array $array)
Pulls out the options hash from $array if any.
at line 1796
string
to_json(array $options = array())
Returns a JSON representation of this model.
at line 1808
string
to_xml(array $options = array())
Returns an XML representation of this model.
at line 1833
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
at line 1845
array
to_array(array $options = array())
Returns an Array representation of this model.
at line 1918
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! });