PHP code example of voskobovich / yii2-linker-behavior
1. Go to this page and download the library: Download voskobovich/yii2-linker-behavior 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/ */
voskobovich / yii2-linker-behavior example snippets
public function getAuthors()
{
return $this->hasMany(
Author::className(),
['id' => 'author_id']
)->viaTable(
'{{%book_has_author}}',
['book_id' => 'id']
);
}
public function getReviews()
{
return $this->hasMany(Review::className(), ['id' => 'review_id']);
}
//...
'author_ids' => [
'authors',
'fields' => [
'json' => [
'get' => function($value) {
//from internal representation (array) to user type
return JSON::encode($value);
},
'set' => function($value) {
//from user type to internal representation (array)
return JSON::decode($value);
},
],
'string' => [
'get' => function($value) {
//from internal representation (array) to user type
return implode(',', $value);
},
'set' => function($value) {
//from user type to internal representation (array)
return explode(',', $value);
},
],
],
]
//...
...
'author_ids' => [
'authors',
'updater' => [
'viaTableAttributesValue' => [
'status_key' => BookHasAuthor::STATUS_ACTIVE,
'created_at' => function() {
return new \yii\db\Expression('NOW()');
},
'is_main' => function($updater, $relatedPk, $rowCondition) {
/**
* $updater this is a object of current updater that implement UpdaterInterface.
* $relatedPk this is a Primary Key of related object.
* $rowCondition this is a object of current row state, that implement AssociativeRowCondition.
*/
/**
* How i can get the Primary Model?
*/
$primaryModel = $updater->getBehavior()->owner;
/**
* How i can get the Primary Key of Primery Model?
*/
$primaryModelPkValue = $primaryModel->getPrimaryKey();
return array_search($relatedPk, $primaryModel->author_ids) === 0;
},
],
]
]
...
function($model, $relationName, $attributeName) {
//get db connection from primary model (Book)
$connection = $model::getDb();
...
//OR get db connection from secondary model (Review)
$secondaryModelClass = $model->getRelation($relationName)->modelClass;
$connection = $secondaryModelClass::getDb();
...
//further value calculation logic (db query)