Db_ActiveRecord

Db_ActiveRecord class is a base class for many other model classes. Containing a range of different methods that enable you to find and update records in the database.

Class methods

$model->find($id)

Finds a record by its identifier.

$model->find_by_[any column name]

Finds a record by a value of any table column. For example, you can load a specific country by its code, using the following code:

$usa = Location_Country::create()->find_by_code('US');

$model->find_all()

Finds all records in the database and returns the Db_DataCollection object, containing a list of found records.

$model->where($query)

Allows to limit the result of the find() and find_all() methods by adding an SQL filter. The following example code returns all orders of a user with ID = 2.

$requests = $request->where('user_id=2')->find_all();

The where method allows to use parameters in the query. That is a preferable way to pass parameters to the query, because parameter values are processed before sending to the database, in order to prevent malicious data corruption.

$requests = $request->where('user_id=?', $user_id)->find_all();

$model->save($data = null)

Saves a record to the database. The optional $data array can be used to set the record field values. Example:

$user = User::create()->find(17);
$user->save(array('first_name'=>'joe'));

Another way to set record field values is the direct access:

$user = User::create()->find(17);
$user->first_name = 'joe';
$user->save();

$model->delete()

Deletes the record from the database.

$model->order($columns)

Sets the result order of the find_all() method by a specific table column. Example:

$posts = Blog_Post::create()->limit(10)->find_all();

$model->limit($number)

Limit the result of the find_all() method with a specified number of records. Example:

$posts = Blog_Post::create()->order('published_at desc')->find_all();

$model->paginate($page_index, $records_per_page)

Allows to limit the result of the find_all method with a single page of record. The parameters are the zero-based page index and a number of records to return on a single page accordingly. Call this method before the find_all method call. The method returns an instance of the Phpr_Pagination class, which you can use to display links to pages.

$model->request_row_count()

returns a number of rows which would be returned if you call the find_all method. This method is efficient in terms of memory usage and SQL queries.