# ActiveRecordInterface

> ActiveRecordInterface.

[API reference](/docs/api/index.md) › [yii](/docs/api/yii/index.md) › [db](/docs/api/yii/db/index.md) › ActiveRecordInterface

| interface | `yii\db\ActiveRecordInterface` |
| --- | --- |
| Extends | [`yii\base\StaticInstanceInterface`](/docs/api/yii/base/staticinstanceinterface/index.md) |
| Since | 2.0 |
| Source | [`framework/db/ActiveRecordInterface.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/db/ActiveRecordInterface.php#L20) |

Implemented by 1 type:

- [`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md)

ActiveRecordInterface.

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`attributes()`](#method-attributes) abstract | Returns the list of all attribute names of the record. | `ActiveRecordInterface` |
| [`delete()`](#method-delete) abstract | Deletes the record from the database. | `ActiveRecordInterface` |
| [`deleteAll()`](#method-deleteAll) static abstract | Deletes records using the provided conditions. | `ActiveRecordInterface` |
| [`equals()`](#method-equals) abstract | Returns a value indicating whether the given active record is the same as the current one. | `ActiveRecordInterface` |
| [`find()`](#method-find) static abstract | Creates an [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance for query purpose. | `ActiveRecordInterface` |
| [`findAll()`](#method-findAll) static abstract | Returns a list of active record models that match the specified primary key value(s) or a set of column values. | `ActiveRecordInterface` |
| [`findOne()`](#method-findOne) static abstract | Returns a single active record model instance by a primary key or an array of column values. | `ActiveRecordInterface` |
| [`getAttribute()`](#method-getAttribute) abstract | Returns the named attribute value. | `ActiveRecordInterface` |
| [`getDb()`](#method-getDb) static abstract | Returns the connection used by this AR class. | `ActiveRecordInterface` |
| [`getIsNewRecord()`](#method-getIsNewRecord) abstract | Returns a value indicating whether the current record is new (not saved in the database). | `ActiveRecordInterface` |
| [`getOldPrimaryKey()`](#method-getOldPrimaryKey) abstract | Returns the old primary key value(s). | `ActiveRecordInterface` |
| [`getPrimaryKey()`](#method-getPrimaryKey) abstract | Returns the primary key value(s). | `ActiveRecordInterface` |
| [`getRelation()`](#method-getRelation) abstract | Returns the relation object with the specified name. | `ActiveRecordInterface` |
| [`hasAttribute()`](#method-hasAttribute) abstract | Returns a value indicating whether the record has an attribute with the specified name. | `ActiveRecordInterface` |
| [`insert()`](#method-insert) abstract | Inserts the record into the database using the attribute values of this record. | `ActiveRecordInterface` |
| <span id="method-instance"></span>[`instance()`](/docs/api/yii/base/staticinstanceinterface/index.md#method-instance) static abstract | Returns static class instance, which can be used to obtain meta information. | [`yii\base\StaticInstanceInterface`](/docs/api/yii/base/staticinstanceinterface/index.md) |
| [`isPrimaryKey()`](#method-isPrimaryKey) static abstract | Returns a value indicating whether the given set of attributes represents the primary key for this model. | `ActiveRecordInterface` |
| [`link()`](#method-link) abstract | Establishes the relationship between two records. | `ActiveRecordInterface` |
| [`populateRelation()`](#method-populateRelation) abstract | Populates the named relation with the related records. | `ActiveRecordInterface` |
| [`primaryKey()`](#method-primaryKey) static abstract | Returns the primary key **name(s)** for this AR class. | `ActiveRecordInterface` |
| [`save()`](#method-save) abstract | Saves the current record. | `ActiveRecordInterface` |
| [`setAttribute()`](#method-setAttribute) abstract | Sets the named attribute value. | `ActiveRecordInterface` |
| [`unlink()`](#method-unlink) abstract | Destroys the relationship between two records. | `ActiveRecordInterface` |
| [`update()`](#method-update) abstract | Saves the changes to this active record into the database. | `ActiveRecordInterface` |
| [`updateAll()`](#method-updateAll) static abstract | Updates records using the provided attribute values and conditions. | `ActiveRecordInterface` |

## Method details

### attributes() <span id="method-attributes"></span>

```php
abstract public function attributes(): array
```

Returns the list of all attribute names of the record.

**Returns**

`array`: List of attribute names.

### delete() <span id="method-delete"></span>

```php
abstract public function delete(): int|bool
```

Deletes the record from the database.

**Returns**

`int|bool`: The number of rows deleted, or `false` if the deletion is unsuccessful for some reason. Note that it is possible that the number of rows deleted is 0, even though the deletion execution is successful.

### deleteAll() <span id="method-deleteAll"></span>

```php
abstract public static function deleteAll(array|null $condition = null): int
```

Deletes records using the provided conditions.

WARNING: If you do not specify any condition, this method will delete ALL rows in the table.

For example, to delete all customers whose status is 3:

```
Customer::deleteAll([status = 3]);
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `array\|null` | The condition that matches the records that should get deleted. Please refer to [`QueryInterface::where()`](/docs/api/yii/db/queryinterface/index.md#method-where) on how to specify this parameter. An empty condition will match all records. |

**Returns**

`int`: The number of rows deleted

### equals() <span id="method-equals"></span>

```php
abstract public function equals(static $record): bool
```

Returns a value indicating whether the given active record is the same as the current one.

Two [new](/docs/api/yii/db/activerecordinterface/index.md#method-getIsNewRecord) records are considered to be not equal.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$record` | `static` | Record to compare to |

**Returns**

`bool`: Whether the two active records refer to the same row in the same database table.

### find() <span id="method-find"></span>

```php
abstract public static function find(): yii\db\ActiveQueryInterface
```

Creates an [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance for query purpose.

The returned [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance can be further customized by calling
methods defined in [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) before `one()` or `all()` is called to return
populated ActiveRecord instances. For example,

```
// find the customer whose ID is 1
$customer = Customer::find()->where(['id' => 1])->one();

// find all active customers and order them by their age:
$customers = Customer::find()
    ->where(['status' => 1])
    ->orderBy('age')
    ->all();
```

This method is also called by [`BaseActiveRecord::hasOne()`](/docs/api/yii/db/baseactiverecord/index.md#method-hasOne) and [`BaseActiveRecord::hasMany()`](/docs/api/yii/db/baseactiverecord/index.md#method-hasMany) to
create a relational query.

You may override this method to return a customized query. For example,

```
class Customer extends ActiveRecord
{
    public static function find()
    {
        // use CustomerQuery instead of the default ActiveQuery
        return new CustomerQuery(get_called_class());
    }
}
```

The following code shows how to apply a default condition for all queries:

```
class Customer extends ActiveRecord
{
    public static function find()
    {
        return parent::find()->where(['deleted' => false]);
    }
}

// Use andWhere()/orWhere() to apply the default condition
// SELECT FROM customer WHERE `deleted`=:deleted AND age>30
$customers = Customer::find()->andWhere('age>30')->all();

// Use where() to ignore the default condition
// SELECT FROM customer WHERE age>30
$customers = Customer::find()->where('age>30')->all();
```

**Returns**

[`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md): The newly created [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md) instance.

### findAll() <span id="method-findAll"></span>

```php
abstract public static function findAll(mixed $condition): array
```

Returns a list of active record models that match the specified primary key value(s) or a set of column values.

The method accepts:

 - a scalar value (integer or string): query by a single primary key value and return an array containing the
   corresponding record (or an empty array if not found).
 - a non-associative array: query by a list of primary key values and return the
   corresponding records (or an empty array if none was found).
   Note that an empty condition will result in an empty result as it will be interpreted as a search for
   primary keys and not an empty `WHERE` condition.
 - an associative array of name-value pairs: query by a set of attribute values and return an array of records
   matching all of them (or an empty array if none was found). Note that `['id' => 1, 2]` is treated as
   a non-associative array.
   Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limted to simple filter conditions.
 - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)

This method will automatically call the `all()` method and return an array of [ActiveRecord](/docs/api/yii/db/activerecordinterface/index.md)
instances.

> Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
> If you need to specify more complex conditions, use [`find()`](/docs/api/yii/db/activerecordinterface/index.md#method-find) in combination with [where()](/docs/api/yii/db/query/index.md#method-where) instead.

See the following code for usage examples:

```
// find the customers whose primary key value is 10
$customers = Customer::findAll(10);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => 10])->all();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findAll([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();

// find customers whose age is 30 and whose status is 1
$customers = Customer::findAll(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();
```

If you need to pass user input to this method, make sure the input value is scalar or in case of
array condition, make sure the array structure can not be changed from the outside:

```
// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `mixed` | Primary key value or a set of column values |

**Returns**

`array`: An array of ActiveRecord instance, or an empty array if nothing matches.

### findOne() <span id="method-findOne"></span>

```php
abstract public static function findOne(mixed $condition): static|null
```

Returns a single active record model instance by a primary key or an array of column values.

The method accepts:

 - a scalar value (integer or string): query by a single primary key value and return the
   corresponding record (or `null` if not found).
 - a non-associative array: query by a list of primary key values and return the
   first record (or `null` if not found).
 - an associative array of name-value pairs: query by a set of attribute values and return a single record
   matching all of them (or `null` if not found). Note that `['id' => 1, 2]` is treated as a non-associative array.
   Column names are limited to current records table columns for SQL DBMS, or filtered otherwise to be limited to simple filter conditions.
 - a yii\db\Expression: The expression will be used directly. (@since 2.0.37)

That this method will automatically call the `one()` method and return an [ActiveRecord](/docs/api/yii/db/activerecordinterface/index.md)
instance.

> Note: As this is a short-hand method only, using more complex conditions, like ['!=', 'id', 1] will not work.
> If you need to specify more complex conditions, use [`find()`](/docs/api/yii/db/activerecordinterface/index.md#method-find) in combination with [where()](/docs/api/yii/db/query/index.md#method-where) instead.

See the following code for usage examples:

```
// find a single customer whose primary key value is 10
$customer = Customer::findOne(10);

// the above code is equivalent to:
$customer = Customer::find()->where(['id' => 10])->one();

// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findOne([10, 11, 12]);

// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->one();

// find the first customer whose age is 30 and whose status is 1
$customer = Customer::findOne(['age' => 30, 'status' => 1]);

// the above code is equivalent to:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();
```

If you need to pass user input to this method, make sure the input value is scalar or in case of
array condition, make sure the array structure can not be changed from the outside:

```
// yii\web\Controller ensures that $id is scalar
public function actionView($id)
{
    $model = Post::findOne($id);
    // ...
}

// explicitly specifying the colum to search, passing a scalar or array here will always result in finding a single record
$model = Post::findOne(['id' => Yii::$app->request->get('id')]);

// do NOT use the following code! it is possible to inject an array condition to filter by arbitrary column values!
$model = Post::findOne(Yii::$app->request->get('id'));
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$condition` | `mixed` | Primary key value or a set of column values |

**Returns**

`static|null`: ActiveRecord instance matching the condition, or `null` if nothing matches.

### getAttribute() <span id="method-getAttribute"></span>

```php
abstract public function getAttribute(string $name): mixed
```

Returns the named attribute value.

If this record is the result of a query and the attribute is not loaded,
`null` will be returned.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name |

**Returns**

`mixed`: The attribute value. `null` if the attribute is not set or does not exist.

**See also**

- [`hasAttribute()`](/docs/api/yii/db/activerecordinterface/index.md#method-hasAttribute)

### getDb() <span id="method-getDb"></span>

```php
abstract public static function getDb(): mixed
```

Returns the connection used by this AR class.

**Returns**

`mixed`: The database connection used by this AR class.

### getIsNewRecord() <span id="method-getIsNewRecord"></span>

```php
abstract public function getIsNewRecord(): bool
```

Returns a value indicating whether the current record is new (not saved in the database).

**Returns**

`bool`: Whether the record is new and should be inserted when calling [`save()`](/docs/api/yii/db/activerecordinterface/index.md#method-save).

### getOldPrimaryKey() <span id="method-getOldPrimaryKey"></span>

```php
abstract public function getOldPrimaryKey(bool $asArray = false): mixed
```

Returns the old primary key value(s).

This refers to the primary key value that is populated into the record
after executing a find method (e.g. find(), findOne()).
The value remains unchanged even if the primary key attribute is manually assigned with a different value.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$asArray` | `bool` | Whether to return the primary key value as an array. If true, the return value will be an array with column name as key and column value as value. If this is `false` (default), a scalar value will be returned for non-composite primary key. |

**Returns**

`mixed`: The old primary key value. An array (column name => column value) is returned if the primary key is composite or `$asArray` is true. A string is returned otherwise (`null` will be returned if the key value is `null`).

### getPrimaryKey() <span id="method-getPrimaryKey"></span>

```php
abstract public function getPrimaryKey(bool $asArray = false): mixed
```

Returns the primary key value(s).

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$asArray` | `bool` | Whether to return the primary key value as an array. If true, the return value will be an array with attribute names as keys and attribute values as values. Note that for composite primary keys, an array will always be returned regardless of this parameter value. |

**Returns**

`mixed`: The primary key value. An array (attribute name => attribute value) is returned if the primary key is composite or `$asArray` is true. A string is returned otherwise (`null` will be returned if the key value is `null`).

### getRelation() <span id="method-getRelation"></span>

```php
abstract public function getRelation(string $name, bool $throwException = true): yii\db\ActiveQueryInterface
```

Returns the relation object with the specified name.

A relation is defined by a getter method which returns an object implementing the [`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md)
(normally this would be a relational [`ActiveQuery`](/docs/api/yii/db/activequery/index.md) object).
It can be declared in either the ActiveRecord class itself or one of its behaviors.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
| `$throwException` | `bool` | Whether to throw exception if the relation does not exist. |

**Returns**

[`ActiveQueryInterface`](/docs/api/yii/db/activequeryinterface/index.md): The relational query object

### hasAttribute() <span id="method-hasAttribute"></span>

```php
abstract public function hasAttribute(string $name): bool
```

Returns a value indicating whether the record has an attribute with the specified name.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The name of the attribute |

**Returns**

`bool`: Whether the record has an attribute with the specified name.

### insert() <span id="method-insert"></span>

```php
abstract public function insert(bool $runValidation = true, array|null $attributes = null): bool
```

Inserts the record into the database using the attribute values of this record.

Usage example:

```
$customer = new Customer;
$customer->name = $name;
$customer->email = $email;
$customer->insert();
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$runValidation` | `bool` | Whether to perform validation (calling [validate()](/docs/api/yii/base/model/index.md#method-validate)) before saving the record. Defaults to `true`. If the validation fails, the record will not be saved to the database and this method will return `false`. |
| `$attributes` | `array\|null` | List of attributes that need to be saved. Defaults to `null`, meaning all attributes that are loaded from DB will be saved. |

**Returns**

`bool`: Whether the attributes are valid and the record is inserted successfully.

### isPrimaryKey() <span id="method-isPrimaryKey"></span>

```php
abstract public static function isPrimaryKey(array $keys): bool
```

Returns a value indicating whether the given set of attributes represents the primary key for this model.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$keys` | `array` | The set of attributes to check |

**Returns**

`bool`: Whether the given set of attributes represents the primary key for this model

### link() <span id="method-link"></span>

```php
abstract public function link(string $name, static $model, array $extraColumns = []): mixed
```

Establishes the relationship between two records.

The relationship is established by setting the foreign key value(s) in one record
to be the corresponding primary key value(s) in the other record.
The record with the foreign key will be saved into database without performing validation.

If the relationship involves a junction table, a new row will be inserted into the
junction table which contains the primary key values from both records.

This method requires that the primary key value is not `null`.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
| `$model` | `static` | The record to be linked with the current one. |
| `$extraColumns` | `array` | Additional column values to be saved into the junction table. This parameter is only meaningful for a relationship involving a junction table (i.e., a relation set with [`ActiveQueryInterface::via()`](/docs/api/yii/db/activequeryinterface/index.md#method-via)). |

**Returns**

`mixed`

### populateRelation() <span id="method-populateRelation"></span>

```php
abstract public function populateRelation(string $name, yii\db\ActiveRecordInterface|array|null $records): mixed
```

Populates the named relation with the related records.

Note that this method does not check if the relation exists or not.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The relation name, e.g. `orders` for a relation defined via `getOrders()` method (case-sensitive). |
| `$records` | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`\|array\|null` | The related records to be populated into the relation. |

**Returns**

`mixed`

**Since**

2.0.8

### primaryKey() <span id="method-primaryKey"></span>

```php
abstract public static function primaryKey(): string[]
```

Returns the primary key **name(s)** for this AR class.

Note that an array should be returned even when the record only has a single primary key.

For the primary key **value** see [`getPrimaryKey()`](/docs/api/yii/db/activerecordinterface/index.md#method-getPrimaryKey) instead.

**Returns**

`string[]`: The primary key name(s) for this AR class.

### save() <span id="method-save"></span>

```php
abstract public function save(bool $runValidation = true, array|null $attributeNames = null): bool
```

Saves the current record.

This method will call [`insert()`](/docs/api/yii/db/activerecordinterface/index.md#method-insert) when [isNewRecord](/docs/api/yii/db/activerecordinterface/index.md#method-getIsNewRecord) is true, or [`update()`](/docs/api/yii/db/activerecordinterface/index.md#method-update)
when [isNewRecord](/docs/api/yii/db/activerecordinterface/index.md#method-getIsNewRecord) is false.

For example, to save a customer record:

```
$customer = new Customer; // or $customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->save();
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$runValidation` | `bool` | Whether to perform validation (calling [validate()](/docs/api/yii/base/model/index.md#method-validate)) before saving the record. Defaults to `true`. If the validation fails, the record will not be saved to the database and this method will return `false`. |
| `$attributeNames` | `array\|null` | List of attribute names that need to be saved. Defaults to `null`, meaning all attributes that are loaded from DB will be saved. |

**Returns**

`bool`: Whether the saving succeeded (i.e. no validation errors occurred).

### setAttribute() <span id="method-setAttribute"></span>

```php
abstract public function setAttribute(string $name, mixed $value): mixed
```

Sets the named attribute value.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The attribute name. |
| `$value` | `mixed` | The attribute value. |

**Returns**

`mixed`

**See also**

- [`hasAttribute()`](/docs/api/yii/db/activerecordinterface/index.md#method-hasAttribute)

### unlink() <span id="method-unlink"></span>

```php
abstract public function unlink(string $name, static $model, bool $delete = false): mixed
```

Destroys the relationship between two records.

The record with the foreign key of the relationship will be deleted if `$delete` is true.
Otherwise, the foreign key will be set `null` and the record will be saved without validation.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The case sensitive name of the relationship, e.g. `orders` for a relation defined via `getOrders()` method. |
| `$model` | `static` | The model to be unlinked from the current one. |
| `$delete` | `bool` | Whether to delete the model that contains the foreign key. If false, the model's foreign key will be set `null` and saved. If true, the model containing the foreign key will be deleted. |

**Returns**

`mixed`

### update() <span id="method-update"></span>

```php
abstract public function update(bool $runValidation = true, array|null $attributeNames = null): int|bool
```

Saves the changes to this active record into the database.

Usage example:

```
$customer = Customer::findOne($id);
$customer->name = $name;
$customer->email = $email;
$customer->update();
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$runValidation` | `bool` | Whether to perform validation (calling [validate()](/docs/api/yii/base/model/index.md#method-validate)) before saving the record. Defaults to `true`. If the validation fails, the record will not be saved to the database and this method will return `false`. |
| `$attributeNames` | `array\|null` | List of attributes that need to be saved. Defaults to `null`, meaning all attributes that are loaded from DB will be saved. |

**Returns**

`int|bool`: The number of rows affected, or `false` if validation fails or updating process is stopped for other reasons. Note that it is possible that the number of rows affected is 0, even though the update execution is successful.

### updateAll() <span id="method-updateAll"></span>

```php
abstract public static function updateAll(array $attributes, mixed $condition = null): int
```

Updates records using the provided attribute values and conditions.

For example, to change the status to be 1 for all customers whose status is 2:

```
Customer::updateAll(['status' => 1], ['status' => '2']);
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$attributes` | `array` | Attribute values (name-value pairs) to be saved for the record. Unlike [`update()`](/docs/api/yii/db/activerecordinterface/index.md#method-update) these are not going to be validated. |
| `$condition` | `mixed` | The condition that matches the records that should get updated. Please refer to [`QueryInterface::where()`](/docs/api/yii/db/queryinterface/index.md#method-where) on how to specify this parameter. An empty condition will match all records. |

**Returns**

`int`: The number of rows updated