Sunday, March 11, 2012

magento -- 如何为商品分类(category)添加自定义属性


在magento中,由于使用了强大的EAV设计方法,我们可以很方便的给商品添加任意数量的属性。然而magento没有给我们提供给商品分类添加属性的功能。尽管我们知道magento所采用的EAV设计方法是完全可以实现的,但是我们又该如何才能给magento的商品分类添加一个属性呢?比如我们想基于产品分类添加一些属性使之应用于产品,或者用来区分产品分类等。

如果不通过magento的方式,直接通过操作数据库,可以按照以下步骤来添加:

step 1,向eav_attribute表插入一条记录。作用是定义一个新属性,并指定这个属性属于商品分类category。先找出magento商品分类(category entity)对应的entity_type_id,并确定好attribute_cod,backend_type,frontend_input,frontend_label,default_value,source_mode的值。如果不确定某个字段应该使用什么值,可以参考一个商品分类其它属性的值来设定。

INSERT INTO eav_attribute
(entity_type_id, attribute_code, backend_type, frontend_input, frontend_label, default_value, source_model)
VALUES
(3, 'category_featured', 'int', 'select', 'Featured Category', '', 'eav/entity_attribute_source_boolean');

注意:一定要确认正确的entity_type_id,不要照搬上面的sql语句,如果不太熟悉可以直接使用phpmyadmin,尽量参照商品分类其它属性的值。

仅仅这一句只是给分类添加了新增的属性,但是那些已经创建的分类是不会有这些属性的,为了让这些分类有新增的属性,还需要向magento的另一个表中插入一条记录。

Step 2,向eav_entity_attribute插入一条记录。其中 entity_type_id和上面得到的是一样的,attribute_id则是上面新插入记录的ID,sort_order则是这个属性在这个属性组中排序的序号。attribute_set_id属性集的ID,attribute_group_id是属性分组的ID。一样的,如果你不能完全确认相应字段的值,可以通过参考商品分类其它属性的值来确定。

INSERT INTO eav_entity_attribute ( entity_type_id, attribute_set_id,attribute_group_id, attribute_id, sort_order ) VALUES ( 3, 3, 3,<new attribute ID>, <next sort order> )

这样你就给magento的商品分类(category)添加了一个新属性,而且已经添加完的分类也会这个新增属性。

那我们如何,才能在magento模板中,或者magento的model,helper,controller的类代码中获取到这个属性的值呢?得益于magento强大的setter,getter,你可以直接使用$category->getAttribute_name()来获取这个属性的值。

(更新: magento 1.6版本)

在magento 1.6版本中,要给分类添加属性,除了上面两个步骤之外还需要在表catalog_eav_attribute插入一条记录,第一个字段为属性ID

INSERT INTO `copybagcom`.`catalog_eav_attribute` (
`attribute_id` ,
`frontend_input_renderer` ,
`is_global` ,
`is_visible` ,
`is_searchable` ,
`is_filterable` ,
`is_comparable` ,
`is_visible_on_front` ,
`is_html_allowed_on_front` ,
`is_used_for_price_rules` ,
`is_filterable_in_search` ,
`used_in_product_listing` ,
`used_for_sort_by` ,
`is_configurable` ,
`apply_to` ,
`is_visible_in_advanced_search` ,
`position` ,
`is_wysiwyg_enabled` ,
`is_used_for_promo_rules`
)
VALUES (
'127', NULL , '1', '1', '0', '0', '0', '1', '1', '0', '0', '0', '0', '0', NULL , '0', '0', '1', '0'
);

No comments:

Post a Comment