Pergunta

Estou tentando adicionar algumas colunas extras no Magento cliente grade.Eu tenho um número de ordem de trabalho com êxito (quantidade Total de pedidos de um cliente tem colocado)

Eu estou tentando pegar a Última Ordem de data, mas eu sou incapaz de fazê-lo funcionar.Alguém já fez isso antes ou alguém pode me apontar na direção certa, como fazer isso?

Este é o meu atual código, mas os erros e apenas exibe uma consulta SQL.

    $orderTableName = Mage::getSingleton('core/resource')
        ->getTableName('sales/order');
    $collection->getSelect()
        ->joinLeft(
            array('orders' => $orderTableName),
            'orders.customer_id=e.entity_id',
            array(
                'order_count' => 'COUNT(customer_id)',
                'last_order' => 'MAX(created_at)'
            )
        );
    $collection->groupByAttribute('entity_id');
Foi útil?

Solução

Aqui está o exemplo de trabalho para o CE 1.8.1:

protected function _prepareCollection()
{
    $collection = Mage::getResourceModel('customer/customer_collection')
        ->addNameToSelect()
        ->addAttributeToSelect('email')
        ->addAttributeToSelect('created_at')
        ->addAttributeToSelect('group_id')
        ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
        ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
        ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
        ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
        ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');



    // add 2 new fields as sub queries      
    $sql ='SELECT MAX(o.created_at)'
        . ' FROM ' . Mage::getSingleton('core/resource')->getTableName('sales/order') . ' AS o'
        . ' WHERE o.customer_id = e.entity_id ';
    $expr = new Zend_Db_Expr('(' . $sql . ')'); 

    $collection->getSelect()->from(null, array('last_order_date'=>$expr));

    $sql ='SELECT COUNT(*)'
        . ' FROM ' . Mage::getSingleton('core/resource')->getTableName('sales/order') . ' AS o'
        . ' WHERE o.customer_id = e.entity_id ';
    $expr = new Zend_Db_Expr('(' . $sql . ')'); 

    $collection->getSelect()->from(null, array('orders_count'=>$expr));

    //echo $collection->getSelect(); exit;      

    $this->setCollection($collection);

    return parent::_prepareCollection();
}

e

protected function _prepareColumns()
{
    $this->addColumn('entity_id', array(
        'header'    => Mage::helper('customer')->__('ID'),
        'width'     => '50px',
        'index'     => 'entity_id',
        'type'  => 'number',
    ));

    $this->addColumn('last_order_date', array(
        'header'    => Mage::helper('customer')->__('Last Order Date'),
        'type'      => 'datetime',
        'align'     => 'center',
        'index'     => 'last_order_date',
        'gmtoffset' => true,        
    ));

    $this->addColumn('orders_count', array(
        'header'    => Mage::helper('customer')->__('Orders Count'),
        'index'     => 'orders_count',
    ));

    ........
    ........

A saída é

orders

Outras dicas

Aqui está como eu faria isso.
Gostaria de criar 2 atributos chamado last_order_date e orders_count a entidade de cliente que são visíveis apenas no back-end.Ou não visível a todos. Aqui está uma maneira possível para adicioná-los.

O que eu iria criar um observador checkout_submit_all_after evento que iria alterar os valores desses atributos.
Algo como isto:

public function checkoutSubmitAllAfter($observer) {
    $order = $observer->getEvent()->getOrder();
    if ($order) { //if on onepage checkout;
        $customer = $order->getCustomer();
        $lastOrderDate = $order->getCreatedAt();
        $increment = 1;
    }
    else { //if on multishipping checkout
       $orders = $observer->getEvent()->getOrders();
       //get last order that's the important one;
       $order = $orders[count($orders) - 1];
       $customer = $order->getCustomer();
       $lastOrderDate = $order->getCreatedAt();
       $increment = count($orders);
    }
    if ($customer && $customer->getId()) { //check if the customer is logged in
       //make sure you have a clean instance of the customer
       //this line may not be needed. Test with it and without it.
       $customer = Mage::getModel('customer/customer')->load($customer->getId());
       //set the new values on the customer entity
       $customer->setLastOrderDate($lastOrderDate);
       $customer->setOrdersCount((int)$customer->getOrdersCount() + $increment);
       $customer->save();
    }
}

Eu não testei o código, para que eu possa ter perdido algo.

Agora você tem os valores que você precisa sobre o objeto cliente e você não precisa de qualquer um louco de associação ou ordem de classificação e, especialmente, não group by.
Você pode adicione o seu 2 novas colunas o cliente grade e você pode até mesmo deixá-los classificáveis e facilmente filtráveis.

Se você já tem clientes em seu banco de dados, então você vai precisar de um, a um só tempo script que define os valores para os clientes existentes.
Mas você pode identificar esses valores facilmente.

Se você precisa apenas de "completar" status like me, em seguida, basta adicionar . ' AND o.status LIKE "complete" ' depois de . ' WHERE o.customer_id = e.entity_id ';

Também adicionei o total de Dinheiro gasto pelo cliente (por isso o total de todos os seus pedidos completos)

    $total_pricesql ='SELECT sum(o.base_grand_total)'
        . ' FROM ' . Mage::getSingleton('core/resource')->getTableName('sales/order') . ' AS o'
        . ' WHERE o.customer_id = e.entity_id ' . ' AND o.status LIKE  "complete" ';
    $expr = new Zend_Db_Expr('(' . $total_pricesql . ')'); 

    $collection->getSelect()->from(null, array('total_price'=>$expr));

e, mais tarde, no mesmo arquivo

    $this->addColumn('total_price', array(
        'header' => Mage::helper('sales')->__('Total'),
        'index' => 'total_price',
        'type'  => 'number',
        'filter'    => false,
    ));

a mudança @Amasty primeira códigos:

protected function _prepareCollection() {
$collection = Mage::getResourceModel('customer/customer_collection')
    ->addNameToSelect()
    ->addAttributeToSelect('email')
    ->addAttributeToSelect('created_at')
    ->addAttributeToSelect('group_id')
    ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
    ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
    ->joinAttribute('billing_telephone', 'customer_address/telephone', 'default_billing', null, 'left')
    ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
    ->joinAttribute('billing_country_id', 'customer_address/country_id', 'default_billing', null, 'left');



// add 3 new fields as sub queries      
$sql ='SELECT MAX(o.created_at)'
    . ' FROM ' . Mage::getSingleton('core/resource')->getTableName('sales/order') . ' AS o'
    . ' WHERE o.customer_id = e.entity_id ' . ' AND o.status LIKE  "complete" ';
$expr = new Zend_Db_Expr('(' . $sql . ')'); 

$collection->getSelect()->from(null, array('last_order_date'=>$expr));

$sql ='SELECT COUNT(*)'
    . ' FROM ' . Mage::getSingleton('core/resource')->getTableName('sales/order') . ' AS o'
    . ' WHERE o.customer_id = e.entity_id ' . ' AND o.status LIKE  "complete" ';
$expr = new Zend_Db_Expr('(' . $sql . ')'); 

$collection->getSelect()->from(null, array('orders_count'=>$expr));

$total_pricesql ='SELECT sum(o.base_grand_total)'
    . ' FROM ' . Mage::getSingleton('core/resource')->getTableName('sales/order') . ' AS o'
    . ' WHERE o.customer_id = e.entity_id ' . ' AND o.status LIKE  "complete" ';
$expr = new Zend_Db_Expr('(' . $total_pricesql . ')'); 

$collection->getSelect()->from(null, array('total_price'=>$expr));

//echo $collection->getSelect(); exit;      

$this->setCollection($collection); return parent::_prepareCollection();}

e o segundo código:

protected function _prepareColumns() {
$this->addColumn('entity_id', array(
    'header'    => Mage::helper('customer')->__('ID'),
    'width'     => '50px',
    'index'     => 'entity_id',
    'type'  => 'number',
));

$this->addColumn('last_order_date', array(
    'header'    => Mage::helper('customer')->__('Last Order Date'),
    'type'      => 'datetime',
    'align'     => 'center',
    'index'     => 'last_order_date',
    'gmtoffset' => true,        
));

$this->addColumn('orders_count', array(
    'header'    => Mage::helper('customer')->__('Orders Count'),
    'index'     => 'orders_count',
));

$this->addColumn('total_price', array(
    'header' => Mage::helper('sales')->__('Total'),
    'index' => 'total_price',
    'type'  => 'number',
    'filter'    => false,
));

........
........

Aqui está como eu resolvi o problema com o filtro e ordenação de trabalho, _prepareCollection:

$collection = Mage::getResourceModel('customer/customer_collection')
    ->addNameToSelect()
    ->joinAttribute('billing_street', 'customer_address/street', 'default_billing', null, 'left')
    ->joinAttribute('billing_city', 'customer_address/city', 'default_billing', null, 'left')
    ->joinAttribute('billing_region', 'customer_address/region', 'default_billing', null, 'left')
    ->joinAttribute('billing_postcode', 'customer_address/postcode', 'default_billing', null, 'left')
;

$sql = sprintf('SELECT MAX(o.created_at) AS created_at FROM %s AS o GROUP BY o.customer_id', Mage::getSingleton('core/resource')->getTableName('sales/order_grid'));
$expr = new Zend_Db_Expr('(' . $sql . ')');

$collection->joinTable(array('order' => 'sales/order_grid'), 'customer_id=entity_id', array('order_created_at' => 'created_at'), "order.created_at IN ($expr)", 'left');

Em seguida, no _prepareColumns:

$this->addColumn('order_created_at', array(
    'header'    => Mage::helper('sales')->__('Purchased On'),
    'type'      => 'datetime',
    'index'     => 'order_created_at',
    'gmtoffset' => true,
));
Licenciado em: CC-BY-SA com atribuição
Não afiliado a magento.stackexchange
scroll top