Skip to content

Handling A Data Model

Alejandro Mostajo edited this page Oct 24, 2019 · 4 revisions

List of static and public methods to handle a model extended from the DataModel class.

NOTE: Samples in this article will be consistent with the model shown in the data model's wiki article.


Insert

static::insert( $attributes )

Parameter Type Description
$attributes array Model attribute values to insert.

Returns: DataModel the inserted model.

Usage sample:

$model = MyModel::insert( ['name' => 'John Doe'] );
echo $model->model_id;

Find

static::find( $id )

Parameter Type Description
$id mixed ID value stored in the primary key column.

Returns: DataModel a filled model if found, null if not found.

Usage sample:

$model = MyModel::find( 1 );

Find Where

static::find_where( $args )

Parameter Type Description
$args array Where statement arguments used to find a record.

Returns: DataModel the first filled model found based on the where arguments, null if not found.

Usage sample:

$model = MyModel::find_where( ['name' => 'John Doe'] );

Delete Where

static::delete_where( $args )

Parameter Type Description
$args array Where statement arguments used to delete multiple records.

Returns: bool.

Usage sample:

$success = MyModel::delete_where( ['type_id' => 1] );

Where

static::where( $args )

Parameter Type Description
$args array Where statement arguments used return multiple records.

Returns: array the collection of records found.

Usage sample:

$models = MyModel::where( ['type_id' => 1] );

Count

static::count( $args )

Parameter Type Description
$args array Where statement arguments used return count.

Returns: int.

Usage sample:

$count = MyModel::count( ['type_id' => 1] );

Builder

static::builder()

Returns: TenQuality\WP\Database\QueryBuilder A query builder initialized with the from() statement filled with the model's table name (the alias as the table's name).

Usage sample:

$builder = MyModel::builder()->select( 'model_table.name' );

Save

Inserts or updates an instantiated model.

save( $force_insert = false )

Parameter Type Description
$force_insert bool Flag that indicates if should insert regardless of ID.

Returns: bool.

Usage sample:

$model = MyModel::find( 1 );

// Update
$model->name = 'Jane Doe';
if ( $model->save() ) {
   echo 'saved';
}

Delete

Deletes an instantiated model.

delete()

Returns: bool.

Usage sample:

$model = MyModel::find( 1 );
if ( $model->delete() ) {
   echo 'deleted';
}
Clone this wiki locally