# ActiveRelationTrait

> ActiveRelationTrait implements the common methods and properties for active record relational queries.

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

| trait | `yii\db\ActiveRelationTrait` |
| --- | --- |
| Since | 2.0 |
| Source | [`framework/db/ActiveRelationTrait.php`](https://github.com/yiisoft/yii2/blob/22.0/framework/db/ActiveRelationTrait.php#L26) |

Used by 1 type:

- [`ActiveQuery`](/docs/api/yii/db/activequery/index.md)

ActiveRelationTrait implements the common methods and properties for active record relational queries.

## Properties

| Property | Type | Description | Defined by |
| --- | --- | --- | --- |
| [`$inverseOf`](#property-inverseOf) | `string` | The name of the relation that is the inverse of this relation. Default: `null`. | `ActiveRelationTrait` |
| [`$link`](#property-link) | `array` | The columns of the primary and foreign tables that establish a relation. Default: `null`. | `ActiveRelationTrait` |
| <span id="property-modelClass"></span>`$modelClass` | `class-string<`[`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`>` |  | `ActiveRelationTrait` |
| [`$multiple`](#property-multiple) | `bool` | Whether this query represents a relation to more than one record. Default: `null`. | `ActiveRelationTrait` |
| [`$primaryModel`](#property-primaryModel) | [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) | The primary model of a relational query. Default: `null`. | `ActiveRelationTrait` |
| [`$via`](#property-via) | `array\|object\|null` | The query associated with the junction table. Default: `null`. | `ActiveRelationTrait` |

## Methods

| Method | Description | Defined by |
| --- | --- | --- |
| [`__clone()`](#method-__clone) | Clones internal objects. | `ActiveRelationTrait` |
| [`all()`](#method-all) | See [`ActiveQueryInterface::all()`](/docs/api/yii/db/queryinterface/index.md#method-all) for more info. | `ActiveRelationTrait` |
| [`findFor()`](#method-findFor) | Finds the related records for the specified primary record. | `ActiveRelationTrait` |
| [`inverseOf()`](#method-inverseOf) | Sets the name of the relation that is the inverse of this relation. | `ActiveRelationTrait` |
| [`one()`](#method-one) | See [`ActiveQueryInterface::one()`](/docs/api/yii/db/activequeryinterface/index.md#method-one) for more info. | `ActiveRelationTrait` |
| [`populateRelation()`](#method-populateRelation) | Finds the related records and populates them into the primary models. | `ActiveRelationTrait` |
| [`via()`](#method-via) | Specifies the relation associated with the junction table. | `ActiveRelationTrait` |

## Property details

### $inverseOf <span id="property-inverseOf"></span>

```php
public string $inverseOf = null
```

The name of the relation that is the inverse of this relation.

For example, an order has a customer, which means the inverse of the "customer" relation
is the "orders", and the inverse of the "orders" relation is the "customer".
If this property is set, the primary record(s) will be referenced through the specified relation.
For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
and accessing the customer of an order will not trigger new DB query.
This property is only used in relational context.

### $link <span id="property-link"></span>

```php
public array $link = null
```

The columns of the primary and foreign tables that establish a relation.

The array keys must be columns of the table for this relation, and the array values
must be the corresponding columns from the primary table.
Do not prefix or quote the column names as this will be done automatically by Yii.
This property is only used in relational context.

### $multiple <span id="property-multiple"></span>

```php
public bool $multiple = null
```

Whether this query represents a relation to more than one record.

This property is only used in relational context. If true, this relation will
populate all query results into AR instances using [all()](/docs/api/yii/db/query/index.md#method-all).
If false, only the first row of the results will be retrieved using [one()](/docs/api/yii/db/query/index.md#method-one).

### $primaryModel <span id="property-primaryModel"></span>

```php
public yii\db\ActiveRecord $primaryModel = null
```

The primary model of a relational query.

This is used only in lazy loading with dynamic query options.

### $via <span id="property-via"></span>

```php
public array|object|null $via = null
```

The query associated with the junction table.

Please call [`via()`](/docs/api/yii/db/activerelationtrait/index.md#method-via)
to set this property instead of directly setting it.
This property is only used in relational context.

## Method details

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

```php
public function __clone(): mixed
```

Clones internal objects.

**Returns**

`mixed`

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

```php
public function all(mixed $db): yii\db\ActiveRecordInterface[]
```

See [`ActiveQueryInterface::all()`](/docs/api/yii/db/queryinterface/index.md#method-all) for more info.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | `mixed` |  |

**Returns**

[`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`[]`

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

```php
public function findFor(string $name, yii\db\ActiveRecordInterface|yii\db\BaseActiveRecord $model): mixed
```

Finds the related records for the specified primary record.

This method is invoked when a relation of an ActiveRecord is being accessed lazily.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The relation name |
| `$model` | [`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`\|`[`BaseActiveRecord`](/docs/api/yii/db/baseactiverecord/index.md) | The primary model |

**Returns**

`mixed`: The related record(s)

**Throws**

- [`yii\base\InvalidArgumentException`](/docs/api/yii/base/invalidargumentexception/index.md): if the relation is invalid

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

```php
public function inverseOf(string $relationName): $this
```

Sets the name of the relation that is the inverse of this relation.

For example, a customer has orders, which means the inverse of the "orders" relation is the "customer".
If this property is set, the primary record(s) will be referenced through the specified relation.
For example, `$customer->orders[0]->customer` and `$customer` will be the same object,
and accessing the customer of an order will not trigger a new DB query.

Use this method when declaring a relation in the [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) class, e.g. in Customer model:

```
public function getOrders()
{
    return $this->hasMany(Order::class, ['customer_id' => 'id'])->inverseOf('customer');
}
```

This also may be used for Order model, but with caution:

```
public function getCustomer()
{
    return $this->hasOne(Customer::class, ['id' => 'customer_id'])->inverseOf('orders');
}
```

in this case result will depend on how order(s) was loaded.
Let's suppose customer has several orders. If only one order was loaded:

```
$orders = Order::find()->where(['id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;
```

variable `$customerOrders` will contain only one order. If orders was loaded like this:

```
$orders = Order::find()->with('customer')->where(['customer_id' => 1])->all();
$customerOrders = $orders[0]->customer->orders;
```

variable `$customerOrders` will contain all orders of the customer.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$relationName` | `string` | The name of the relation that is the inverse of this relation. |

**Returns**

`$this`: The relation object itself.

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

```php
public function one(mixed $db): yii\db\ActiveRecordInterface|array|null
```

See [`ActiveQueryInterface::one()`](/docs/api/yii/db/activequeryinterface/index.md#method-one) for more info.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$db` | `mixed` |  |

**Returns**

[`ActiveRecordInterface`](/docs/api/yii/db/activerecordinterface/index.md)`|array|null`

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

```php
public function populateRelation(string $name, array &$primaryModels): array
```

Finds the related records and populates them into the primary models.

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$name` | `string` | The relation name |
| `$primaryModels` | `array` | Primary models |

**Returns**

`array`: The related models

**Throws**

- [`yii\base\InvalidConfigException`](/docs/api/yii/base/invalidconfigexception/index.md): if [`$link`](/docs/api/yii/db/activerelationtrait/index.md#property-link) is invalid

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

```php
public function via(string $relationName, callable|null $callable = null): $this
```

Specifies the relation associated with the junction table.

Use this method to specify a pivot record/table when declaring a relation in the [`ActiveRecord`](/docs/api/yii/db/activerecord/index.md) class:

```
class Order extends ActiveRecord
{
   public function getOrderItems() {
       return $this->hasMany(OrderItem::class, ['order_id' => 'id']);
   }

   public function getItems() {
       return $this->hasMany(Item::class, ['id' => 'item_id'])
                   ->via('orderItems');
   }
}
```

**Parameters**

| Parameter | Type | Description |
| --- | --- | --- |
| `$relationName` | `string` | The relation name. This refers to a relation declared in [`$primaryModel`](/docs/api/yii/db/activerelationtrait/index.md#property-primaryModel). |
| `$callable` | `callable\|null` | A PHP callback for customizing the relation associated with the junction table. Its signature should be `function($query)`, where `$query` is the query to be customized. |

**Returns**

`$this`: The relation object itself.