在我的资源模型中,我将字段定义为可序列化(请参阅属性 $_serializableFieldsMage_Core_Model_Resource_Db_Abstract):Magento在加载数据库和保存对象之前,在加载数据时会自动处理内容。

这可以很好地工作,但是当我迭代这些对象的集合时,字段内容并非自动不受欢迎。我尝试了 $collection->walk('afterLoad') 但是很快意识到 unserializeFields() 在资源模型中触发 load(), ,不在 afterLoad() 就像我第一次想到。在这种情况下,最好的做法是什么?如何自动获得该领域?我当然可以在循环中重新加载对象,做类似的事情 $object = $object->load($object->getId()), ,但我想知道是否有一种更聪明的方法来实现这一目标。

有帮助吗?

解决方案

我当然可以在循环中重新加载对象,做类似的事情 $object = $object->load($object->getId())

这是 不是 重新加载 - 这是负载. 。集合中的项目(模型实例) 不是 加载。他们只是将结果行数据应用于他们。这是这些集合拥有的模型实例与通过其资源模型自动加载数据的重要差异。

在您的收藏中 _afterLoad(), ,迭代 _itemsunserialize() 适当的字段:

protected function _afterLoad()
{
    parent::_afterLoad();
    foreach ($this->getItems() as $item) {
        $item->setData('field',unserialize($item->getData('field')));
        $item->setDataChanges(false);
        //The above sets items as not dirty.
        //Value will be serialized on save via resource model.
    }
    return $this;
}

其他提示

为此,我为产品收集添加了一个活动听众 catalog_product_collection_load_after 并迭代所有产品。

/**
 * Apply backend manipulations of attributes to collection items.
 * Listens to catalog_product_collection_load_after.
 *
 * @param Varien_Event_Observer $observer
 * @return Mage_Catalog_Model_Observer
 */
public function loadCollectionAttributes(Varien_Event_Observer $observer)
{
    $collection = $observer->getCollection();
    /* @var $collection Mage_Catalog_Model_Resource_Product_Collection */
    foreach ($collection as $product) {
        /* @var $product Limora_Catalog_Model_Product */
        foreach ($product->getAttributes() as $attribute) {
            /* @var $attribute Mage_Eav_Model_Attribute */
            $attribute->getBackend()->afterLoad($product);
        }
    }
}

或更简单地,在您的资源模型集合中: -

class Collection 
extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    protected function _afterLoad()
    {
        parent::_afterLoad();
        foreach ($this->getItems() as $item) {
            $this->getResource()->unserializeFields($item);
            $item->setDataChanges(false);
        }
        return $this;
   }
}
许可以下: CC-BY-SA归因
scroll top