PHPackages                             sam-it/yii2-virtual-fields - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. sam-it/yii2-virtual-fields

ActiveLibrary[Database &amp; ORM](/categories/database)

sam-it/yii2-virtual-fields
==========================

Implementation of virtual fields for Yii2 AR

v4.2.1(1y ago)230.5k2MITPHPPHP &gt;= 8.1

Since Jun 2Pushed 1y agoCompare

[ Source](https://github.com/SAM-IT/yii2-virtual-fields)[ Packagist](https://packagist.org/packages/sam-it/yii2-virtual-fields)[ RSS](/packages/sam-it-yii2-virtual-fields/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (10)Dependencies (9)Versions (13)Used By (0)

yii2-virtual-fields
===================

[](#yii2-virtual-fields)

Implementation of virtual fields for Yii2 AR

To work this library needs to change 2 parts of the Yii2 ORM.

- The model definitions
- The query implementation

Configuration
=============

[](#configuration)

The change to `ActiveQuery` are simple and can be applied using a trait or a behavior. In case you did not subclass `ActiveQuery` you can choose to attach the behavior dynamically.

```
use SamIT\Yii2\VirtualFields\VirtualFieldQueryBehavior;
use SamIT\Yii2\VirtualFields\VirtualFieldBehavior;
use yii\db\ActiveRecord;
use yii\db\ActiveQuery;
class Author extends ActiveRecord
{
    /**
     * Attach the behavior after constructing the query object
     * @return ActiveQuery
     */
    public static function find()
    {
        $query = parent::find();
        $query->attachBehavior(VirtualFieldQueryBehavior::class, VirtualFieldQueryBehavior::class);
        return $query;
    }

    public function getPosts(): ActiveQuery
    {
        return $this->hasMany(Post::class, ['author_id' => 'id']);
    }

    public function behaviors()
    {
        return [
            VirtualFieldBehavior::class => [
                'class' => VirtualFieldBehavior::class,
                'virtualFields' => [
                    'postCount' => [
                        VirtualFieldBehavior::LAZY => function(Author $author) { return $author->getPosts()->count(); },
                        VirtualFieldBehavior::CAST => VirtualFieldBehavior::CAST_INT,
                        VirtualFieldBehavior::GREEDY => Post::find()
                            ->andWhere('[[author_id]] = [[author]].[[id]]')
                            ->limit(1)
                            ->select('count(*)')
                    ],
                    'postCount2' => [
                        VirtualFieldBehavior::LAZY => function(Author $author) { return $author->getPosts()->count(); },
                        VirtualFieldBehavior::CAST => VirtualFieldBehavior::CAST_INT,
                        // Sometimes you might want to defer loading of your greedy definition in such cases you may supply a closure.
                        // This closure will be called only once
                        VirtualFieldBehavior::GREEDY => static fn() => Post::find()
                            ->andWhere('[[author_id]] = [[author]].[[id]]')
                            ->limit(1)
                            ->select('count(*)')
                    ]
                ]
            ]
        ];
    }

}
```

Since Yii uses the DI container to create the object, it is also possible to add the behavior globally by defining it in the DI container. Virtual fields allow you to define model attributes as SQL fragments. The advantage of this implementation is that it supports both lazy and greedy loading.

Usage
=====

[](#usage)

The library will then take care of everything:

```
    Author::findByPk(1)->postCount; // Lazy loaded
    Author::find()->withField('postCount')->one()->postCount; // Greedy loaded
```

If lazy loading is not implemented and an attribute is used lazily, an exception will be thrown. If greedy loading is not implemented and the field is added to select the normal Yii2 / SQL exception is thrown.

We found these classes greatly helped us in reducing the number of queries (implementing `getPostCount()` on `Author` is not ideal).

To maximize compatibility and minimize issues we chose not to use joins, since they can potentially affect the number of records. In a number of cases the resulting query plan could be less than optimal.

We chose not to overload `ActiveQuery::select()` to support virtual fields. Reason for this is the fact that it changes the semantics of `*`; `*` would not by default include all virtual fields.

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance31

Infrequent updates — may be unmaintained

Popularity32

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 98% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~150 days

Recently: every ~167 days

Total

11

Last Release

718d ago

Major Versions

v1.0.0 → v2.0.02020-06-02

v2.1.0 → v3.0.02022-02-24

v3.0.0 → v4.0.02022-09-13

PHP version history (2 changes)v1.0.0PHP &gt; 7.3

v3.0.0PHP &gt;= 8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/18b13c534e3812b66a72645fe215301b54fc4d288f6396fee9385b681e27da18?d=identicon)[SamMousa](/maintainers/SamMousa)

---

Top Contributors

[![SamMousa](https://avatars.githubusercontent.com/u/547021?v=4)](https://github.com/SamMousa "SamMousa (49 commits)")[![laszlovl](https://avatars.githubusercontent.com/u/12112486?v=4)](https://github.com/laszlovl "laszlovl (1 commits)")

###  Code Quality

TestsCodeception

Static AnalysisPHPStan, Psalm

Code StyleECS

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sam-it-yii2-virtual-fields/health.svg)

```
[![Health](https://phpackages.com/badges/sam-it-yii2-virtual-fields/health.svg)](https://phpackages.com/packages/sam-it-yii2-virtual-fields)
```

###  Alternatives

[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k117.2M118](/packages/jdorn-sql-formatter)[propel/propel1

Propel is an open-source Object-Relational Mapping (ORM) for PHP5.

8351.6M87](/packages/propel-propel1)[pgvector/pgvector

pgvector support for PHP

198741.5k12](/packages/pgvector-pgvector)[jfelder/oracledb

Oracle DB driver for Laravel

11518.4k](/packages/jfelder-oracledb)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
