最新消息:Excel无乱码转CSV,由于工作原因很少更新博客和回复大家的评论,非常抱歉。

在 Magento 中如何使用集合查询条件

集合是一个包含其他型号的机种型号,它基本上是用在Magento处理的产品清单(即从类别或捆绑选项),但不是唯一的。

TO DO:解释如何Magento的实现集合 – 使用此解释如何Magento的实现代码模型中的一个集合,使人们可以学会写自己的藏品

这是一个简单的例子,加载一些产品集合从一个类别,并命令他们在自己的产品名称使用Magento的API的。

$collection = Mage::getModel('catalog/category')->load($categoryId)
    ->getProductCollection()
    ->addAttributeToSort('name', 'ASC');

使用多个字段排序,您可以调用链接到该集合的方法 addAttributeToSort(preferred)

$collection = Mage::getModel('module/model_name')->getCollection()
    ->addAttributeToSort('order', 'ASC')
    ->addAttributeToSort('last_name', 'ASC')
    ->addAttributeToSort('first_name', 'ASC')

TODO:使用Magento的API使用的情况下,不是Zend_Db_Select的。

您也可以通过IF/THEN语句,但一定要使用正确引用表的字段。

$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->order( array('IF(`order`>0, `order`, 9999) ASC',
     'last_name ASC', 'first_name ASC') );

在此示例中,将按顺序字段,排序表然后按上次的名称,然后按名字、 凡订单是否大于零,是秩序正在小于或等于零,所有升序。

联接表

若要添加 SQL 联接到选择

$collection = Mage::getModel('module/model_name')->getCollection();
$collection->getSelect()->join( array('table_alias'=>$this->getTable('module/table_name')), 'main_table.foreign_id = table_alias.primary_key', array('table_alias.*'), 'schema_name_if_different');

在此示例中的联接方法采用 alias⇒table_name 密钥对,然后使用 main_table 引用原始的选择中,标准的 join 子句的数组然后在联接中要检索的字段的数组 (默认为 *),可以作为最后一个参数指定不同的架构。

复审 → 默认为内部联接,其他人可以使用:

→joinInner() →joinLeft() →joinRight() →joinFull() →joinCross() →joinNatural()

请参阅 lib/Zend/Db/Select.php 的源码。

集合操作方法

Varien_Data_Collection
Varien/Data/Collection.php

addFilter($field, $value, $type = ‘and’)
addItem(Varien_Object $item)
clear()
count()
distinct($flag)
each($obj_method, $args=array())
getAllIds()
getCacheKey()
getCacheLifetime()
getCacheTags()
getColumnValues($colName)
getCurPage($displacement = 0)
getFirstItem()
getFlag($flag)
getItemByColumnValue($column, $value)
getItemById($idValue)
getItems()
getItemsByColumnValue($column, $value)
getIterator()
getLastItem()
getLastPageNumber()
getNewEmptyItem()
getPageSize()
getSize()
hasFlag($flag)
isLoaded()
loadData($printQuery = false, $logQuery = false)
load($printQuery = false, $logQuery = false)
removeItemByKey($key)
setCacheKey($key)
setCacheTags($tags)
setCurPage($page)
setDataToAll($key, $value=null)
setFlag($flag, $value = null)
setOrder($field, $direction = self::SORT_ORDER_DESC)
setPageSize($size)
toArray($arrRequiredFields = array())
toOptionArray()
toOptionHash()
toXml()
walk($callback, array $args=array())

Varien_Data_Collection_Db
Varien/Data/Collection/Db.php
继承Varien_Data_Collection,除了上面的方法(重新)定义如下:

addBindParam($name, $value)
addFieldToFilter($field, $condition=null)
addOrder($field, $direction = self::SORT_ORDER_DESC)
distinct($flag)
getConnection()
getData()
getIdFieldName()
getSelect()
getSelectCountSql()
getSize()
initCache($object, $idPrefix, $tags)
loadData($printQuery = false, $logQuery = false)
load($printQuery = false, $logQuery = false)
printLogQuery($printQuery = false, $logQuery = false, $sql = null)
resetData()
setConnection($conn)
setOrder($field, $direction = self::SORT_ORDER_DESC)
unshiftOrder($field, $direction = self::SORT_ORDER_DESC)

筛选器的条件代码

Attribute Code SQL Equivalent Description
eq =
neq !=
like LIKE
nlike NOT LIKE
in IN ()
nin NOT IN ()
is IS
notnull IS NOT NULL
null IS NULL
moreq >=
gt >
lt <
gteq >=
lteq <=
finset FIND_IN_SET()
from >= for use with dates
to <= for use with dates
date optional flag for use with from/to to specify that comparison value should first be converted to a date
datetime optional flag for use with from/to to specify that comparison value should first be converted to a datetime

如果传递的数组,但没有属性代码指定,它将被解释为一组 OR 条件将在相同的方式进行处理。

如果不指定了任何属性代码,则其默认值为不等。
例如:

$collection->addAttributeToFilter('field_name', array(
    'in' => array(1, 2, 3),
    ));

$collection->addAttributeToFilter('date_field', array(
   'from' => '2000-09-10',
    ));

$collection->addAttributeToFilter('date_field', array(
    'from' => '10 September 2000',
    'to' => '11 September 2000',
    'date' => true, // specifies conversion of comparison values
    ));
$collection->addAttributeToFilter('field_name', array(
    'notnull' => true,
    ));

$collection->addAttributeToFilter('field_name', 1); // tests for equality

// Add OR condition:
$collection->addAttributeToFilter(array(
    array(
        'attribute' => 'field_name',
        'in'        => array(1, 2, 3),
        ),
    array(
        'attribute' => 'date_field',
        'from'      => '2000-09-10',
        ),
    ));

Mage_Eav_Model_Entity_Collection
Mage/Eav/Model/Entity/Collection/Abstract.php
继承上述方法Varien_Data_Collection_Db,除了(重新)定义了以下:

addAttributeToFilter($attribute, $condition=null, $joinType=’inner’) adds WHERE clause on $attribute specified by $condition
addAttributeToSelect($attribute, $joinType=false) gets the value for $attribute in the SELECT clause;
specify * to get all attributes (i.e. to execute SELECT *)
addAttributeToSort($attribute, $dir=’asc’) adds ORDER BY clause on $attribute
addEntityTypeToSelect($entityType, $prefix) doesn’t seem to do anything – don’t use
addExpressionAttributeToSelect($alias, $expression, string|array $attribute) adds SQL expression $expression, using $alias, to SELECT clause (typically containing aggregate functions such as SUM()COUNT());
when $attribute specifies a single attribute as a string, $expression can reference the attribute as simply {{attribute}}, but when passing an array of attributes, each attribute must be referenced in $expression by the name of the specific attribute;
N.B. use with groupByAttribute() when including aggregate functions q.v.
addFieldToFilter($attribute, $condition=null) alias for addAttributeToFilter()
addItem(Varien_Object $object) adds an object to the collection
addStaticField($field) specifies $field as being static, i.e. as existing on the entity table itself, rather than in the EAV table
delete() deletes all entities in the collection
exportToArray() returns collection data as a 2D array
getAllIds($limit=null, $offset=null) returns array of all entity IDs selected by current WHERE clause (optionally specifying $limit and $offset)
getAllIdsSql() not recommended – don’t use
getAttribute($attributeCode) for specified $attributeCode, returnsMage_Eav_Model_Entity_Attribute_Abstract object of the entity object used by the collection (i.e. calls getAttribute($attributeCode) on the entity object and returns the result)
getEntity() returns Mage_Eav_Model_Entity_Abstract object used by collection for attributes
getLoadedIds() returns array of IDs of currently loaded entities
getResource() returns Mage_Core_Model_Resource_Abstract instance;
actually an alias for getEntity() q.v. (an entity is a special type of resource, that is, Mage_Eav_Model_Entity_Abstract extendsMage_Core_Model_Resource_Abstract)
getRowIdFieldName() returns field name of ID attribute for entities in the collection
getTable($table) alias for Mage::getSingleton(‘core/resource’)->getTableName($table)
groupByAttribute($attribute) adds $attribute to GROUP BY clause
importFromArray($arr) imports 2D array into collection as objects
joinAttribute($alias, Mage_Eav_Model_Entity_Attribute_Abstract|string $attribute, string $bind, string $filter=null, string $joinType=’inner’, $storeId=null) joins another entity and adds attribute from joined entity, using $alias, to SELECT clause;
$attribute can specify attribute object, or string in format[entity]/[attribute];
$bind specifies attribute of the main entity on which to make join;
$filter specifies primary key of the joined entity on which to make join (normally defaults to entity_id);
$joinType should be inner or left
joinField($alias, $table, $field, $bind, $cond=null, $joinType=’inner’) joins regular table field using an attribute as foreign key
joinTable($table, $bind, $fields=null, $cond=null, $joinType=’inner’) joins table $table
load($printQuery = false, $logQuery = false) runs query and load data into collection;
specify $printQuery as true to print SQL for debugging
removeAttributeToSelect($attribute=null) removes $attribute from SELECT clause;
specify null to remove all attributes
save() saves all entities in the collection
setEntity(string|object $entity) sets entity object (i.e. Mage_Eav_Model_Entity_Abstract) used by collection for attributes
setObject(Varien_Object $object=null) sets template object for the collection
setOrder(string| $attribute, $dir=’desc’) alias for addAttributeToSort() q.v., identical except that it can accept array of attributes, and default $dir is desc;
N.B. overrides parent function
setPage($pageNum, $pageSize) sets LIMIT clause by specifying page number (one-indexed) and number of records per page;
N.B. equivalent to calling setCurPage($pageNum) andsetPageSize($pageSize) q.q.v.
setRowIdFieldName($fieldName) returns field name of ID attribute for entities in the collection
toArray(array $arrAttributes=array()) calls toArray($attAttributes) on each entity in collection, and returns result as array

转载请注明:嗨酷哥,有你更酷! » 在 Magento 中如何使用集合查询条件

与本文相关文章

发表我的评论

取消评论
表情 插代码

Hi,您需要填写昵称和邮箱!

  • 必填项
  • 必填项

网友评论2条  本站回复1

  1. 不错。。。。

    死飞2014-01-25 11:26 回复
  2. 强大的谷歌翻译

    qqq2013-02-28 15:56 回复
    • 没办法,自己看能满足了。

      hicoogle2013-02-28 20:01 回复