PHP code example of sam-it / yii2-virtual-fields

1. Go to this page and download the library: Download sam-it/yii2-virtual-fields library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sam-it / yii2-virtual-fields example snippets


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(*)')
                    ]       
                ]
            ]
        ];
    }

}

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