Архитектура баз данных EAV(Enity-Attribute-Value, Сущность-Атрибут-Значение)
"repositories": [
{
"type": "git",
"url": "https://github.com/mirocow/yii2-eav.git"
}
]
and then
php composer.phar require --prefer-dist "mirocow/yii2-eav" "*"
php ./yii migrate/up -p=@mirocow/eav/migrations
or
php ./yii migrate/up -p=@vendor/mirocow/yii2-eav/src/migrations
class Product extends \yii\db\ActiveRecord
{
/**
* create_time, update_time to now()
* crate_user_id, update_user_id to current login user id
*/
public function behaviors()
{
return [
'eav' => [
'class' => \mirocow\eav\EavBehavior::className(),
// это модель для таблицы object_attribute_value
'valueClass' => \mirocow\eav\models\EavAttributeValue::className(),
]
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getEavAttributes()
{
return \mirocow\eav\models\EavAttribute::find()
->joinWith('entity')
->where([
'categoryId' => $this->categories[0]->id,
'entityModel' => $this::className()
]);
}
}
Insert this code for create widget or load all EAV inputs fields for model
fo load selected field
<?=$form->field($model,'test5', ['class' => '\mirocow\eav\widgets\ActiveField'])->eavInput(); ?>
or for load all fields
<?php
foreach($model->getEavAttributes()->all() as $attr){
echo $form->field($model, $attr->name, ['class' => '\mirocow\eav\widgets\ActiveField'])->eavInput();
}
?>
<p>
Encode
<?php
foreach($model->getEavAttributes()->all() as $attr){
print_r($model[$attr->name]['value']);
}
?>
</p>
<p>
String
<?php
foreach($model->getEavAttributes()->all() as $attr){
echo $model[$attr->name];
}
?>
$attr = new mirocow\eav\models\EavAttribute();
$attr->attributes = [
'entityId' => 1, // Category ID
'name' => 'AttrCategory1', // service name field
'label' => 'Attr1', // label text for form
'defaultValue' => 'attr1', // default value
'entityModel' => SampleModel::className(), // work model
'required'=>false // add rule "required field"
];
$attr->save();
<?= \mirocow\eav\admin\widgets\Fields::widget([
'model' => $model,
'categoryId' => $model->id,
'entityName' => 'Продукт',
'entityModel' => 'common\models\Product',
])?>