Fork me on GitHub

EAV behavior

Добавляет модели возможность работать с eav-моделью данных.

Установка и настройка

Создать таблицу для храниениея EAV-аттрибутов

SQL для таблицы:

CREATE TABLE IF NOT EXISTS `eavAttr` (
  `entity` bigint(20) unsigned NOT NULL,
  `attribute` varchar(250) NOT NULL,
  `value` text NOT NULL,
  KEY `ikEntity` (`entity`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8;

Подключить поведение к модели

function behaviors() {
    return array(
        'eavAttr' => array(
            'class' => 'ext.yiiext.behaviors.model.eav.EEavBehavior',
            // Имя таблицы для аттрибутов (обязательное свойство)
            'tableName' => 'eavAttr',
            // Имя столбца где хранится ид объекта.
            // По умолчанию 'entity'
            'entityField' => 'entity',
            // Имя столбца где хранится имя атрибута.
            // По умолчанию 'attribute'
            'attributeField' => 'attribute',
            // Имя столбца где хранится значение атрибута.
            // По умолчанию 'value'
            'valueField' => 'value',
            // Имя внешнего ключа модели.
            // По умолчанию берется primaryKey из свойста таблицы
            'modelTableFk' => primaryKey,
            // Массив разрешенных атрибутов, если не указано разрешаются любые атрибуты
            // По умолчанию не указано.
            'safeAttributes' => array(),
            // Префикс для атрибутов. Если для разных моделей используется одна таблица.
            // По умолчанию не указано.
            'attributesPrefix' => '',
        )
    );
}

Методы

getEavAttributes($attributes)

Возвращает массив значений атрибутов, индексированные именем атрибута.

$user = User::model()->findByPk(1);
$user->getEavAttributes(array('attribute1', 'attribute2'));

getEavAttribute($attribute)

Возвращает значение атрибута.

$user = User::model()->findByPk(1);
$user->getEavAttribute('attribute1');

setEavAttribute($attribute, $value, $save = FALSE)

Устанавливает значение атрибута.

$user = User::model()->findByPk(1);
$user->setEavAttribute('attribute1', 'value1');

setEavAttributes($attribute, $save = FALSE)

Устанавливает значение атрибутов.

$user = User::model()->findByPk(1);
$user->setEavAttributes(array('attribute1' => 'value1', 'attribute2' => 'value2'));

withEavAttributes($attributes)

Позволяет ограничить запрос AR записями с указанными атрибутами.

$users = User::model()->withEavAttributes(array('skype'))->findAll();
$usersCount = User::model()->withEavAttributes(array('skype'))->count();

Changelog

0.5

[] Fixed error on get attribute without preload. [] Extension is now compatible only with Yii 1.1. [] Changed translation category to 'yiiext'. [] New naming conventions.

0.4

Warning: this version is not backwards compatible to 0.3.

[+] Added lazy-loading attributes. [+] Added caching attributes, set CacheId. [] Added additional boolean parameter $save for methods setEavAttribute, setEavAttributes, deleteEavAttributes, for save immediately. [+] Added method saveEavAttributes(). [+] Added method deleteEavAttributes(). [] Deleted findByEavAttributes() and findAllByEavAttributes() method. Use withEavAttributes(). [+] New syntax: $contacts = Contact::model()->withEavAttributes(array('skype' => 'yii'))->findAll(). [+] Added init test. [+] Added setAttributes method. [] setEavAttribute now return owner CActiveRecord. [] Fixed deleting eav-attributes after delete models. [] Fixed saving array of attribute values. [] Fixed saving secondary change for attribute value. [] Added translation for messages. [+] English readme. [] Corrected english descriptions. [] getEavAttribute now returns null if attribute is not defined. [] Minor code improvements.

0.3

[-] Deleted method readEavAttributes [+] Search model by eav-attribute set [+] All queries in DB will generated by CDbCriteria [] Method saveEavAttributes changed to saveEavAttribute to allow to save each attribute [] Method getModelTableFk now returns value of primary key. To get FK name use getModelTableFkField

0.2

[-] AR for each eav-attribute

0.1

[+] Initial public release.

Implements entity-attribute-value pattern.

Documentation

Downloads (Tags)

Resources