我为用户创建了一个自定义属性is_buyer,该属性将在订单发布事件后设置为1。
现在,我想为至少有一个订单的老用户设置"is_buyer"为1。
我可以使用foreach循环来实现这一点,但我希望使用单个查询来实现。
任何人都知道如何使用magento为上述任务编写查询。
我已经使用循环编写了一次脚本。
<?php
set_time_limit(0);
$customers = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('entity_id')
->addAttributeToFilter(array(array('attribute' => 'is_buyer', 'null' => true)), '', 'left');
$orders = Mage::getSingleton('sales/order')->getCollection()
->addAttributeToSelect('customer_id');
foreach ($customers as $customer) {
$orders->addFieldToFilter('customer_id', $customer->getId());
if ($orders->count() > 0) {
$customer->setData('is_buyer', 1);
} else {
$customer->setData('is_buyer', 0);
}
$customer->save();
}
您可以使用这种缓慢的方法一次性设置旧用户。使用观察者为新订单临时设置客户信息。因此,您只需要运行上述脚本一次。实际上,您可以进行一些性能调整。。。foreach中的保存和加载是一种糟糕的做法,但由于您只需要运行一个脚本,所以这可能无关紧要。。。
$customers = Mage::getModel('customer/customer)->getCollection();
foreach ($customers as $_customer){
$_orders = Mage::getModel('sales/order')->getCollection()->addFieldToFilter('customer_id',$_customer->getId());
if ($_orders->count()){
$customer->setIsBuyer();
$customer->save();
}
}
事件是:
<sales_order_place_after>
<observers>
<your_observer>
<type>singleton</type>
<class>YOUR_CLASS</class>
<method>YOUR_METHOD</method>
</your_observer>
</observers>
</sales_order_place_after>
实际观察者方法(概念验证,但速度较慢):
public static function YOUR_METHOD($observer) {
$event = $observer->getEvent();
$order = $event->getOrder();
$order->getCustomerId();
$customer = Mage::getModel('customer/customer')->load($order->getCustomerId());
$customer->setIsBuyer();
$customer->save();
}
所以这里有安装程序代码,它可以在一个查询中完成这项工作,而不是循环。
/** @var Mage_Customer_Model_Entity_Setup $setup */
$setup = $this;
$setup->startSetup();
$setup->addAttribute('customer', 'is_buyer', array(
'type' => 'int',
'input' => 'boolean',
'label' => 'Is Buyer',
'global' => 1,
'visible' => 1,
'required' => 0,
'user_defined' => 0,
'default' => '0',
'visible_on_front' => 0,
'position' => 200
));
$attributeId = $this->getAttributeId('customer', 'is_buyer');
$setup->run("
INSERT INTO customer_entity_int (`entity_type_id`, `attribute_id`, `entity_id`, `value`)
SELECT 1, {$attributeId}, c.entity_id, 1
FROM customer_entity c
WHERE c.entity_id IN (
SELECT s.customer_id FROM sales_flat_order s
WHERE s.customer_id IS NOT NULL
GROUP BY s.customer_id
)
ON DUPLICATE KEY UPDATE `value` = VALUES(`value`);
");