Yii2 join condition when you use viaTable

Sometimes you need add specific condition in query to via table in yii2.
Example, you need to get categories where clients with active subscribe status(subscribed == true) only:

//standard using viatable without condition(s)
 public function getCategories()
    {
        return $this->hasMany(Categories::className(), ['id' => 'category_id'])
            ->viaTable('categories_xref', ['client_id' => 'id']);
    }

Solution with condition in yii2 via table query:

 public function getCategories()
    {
        return $this->hasMany(Categories::className(), ['id' => 'category_id'])
            ->viaTable('categories_xref', ['client_id' => 'id'], function ($query) {
                $query->onCondition(['subscribed' => true]);
            });
    }

Easy. Happy codding!

UPDATE with random number between range 1-n [MYSQL UPDATE RAND]

Sometimes you need to update your latest added field in DB table by random numbers.
For that reason you can use this simple SQL command:
[1 – min, 100-max]

UPDATE `...` 
SET `columnName` = FLOOR( 1 + RAND( ) *100 );
WHERE ...

In this way you can easy update `columnName` by random value in defined range.
Happy SQLing… Continue reading UPDATE with random number between range 1-n [MYSQL UPDATE RAND]