【问题标题】:Magento: How to search programmatically in customer collectionMagento:如何在客户集合中以编程方式搜索
【发布时间】:2014-11-13 22:42:11
【问题描述】:

我正在尝试构建一个搜索脚本来从客户集合中检索条目。诀窍是正常的“OR”条件仅适用于第一个条目。

这是我目前的代码:

$customers = Mage::getResourceModel('customer/customer_collection')
        ->addAttributeToSelect('*');

    if($_searchTerm = $this->getRequest()->getParam('q')){
        $customers->addAttributeToFilter(
            array(
                array('attribute' => 'firstname', 'like' => $_searchTerm),
                array('attribute' => 'lastname', 'like' => $_searchTerm),
                array('attribute' => 'email', 'like' => '%' . $_searchTerm . '%'),
                array('attribute' => 'phone', 'like' => '%' . $_searchTerm . '%'), /* valid field in my collection*/
            )
        );
    }

我也尝试过使用通配符“%”,但仍然没有正确的结果。 我很可能在这里遗漏了一些东西。

谢谢。

【问题讨论】:

  • 我觉得没问题。当我测试上述结果查询时,预期以WHERE ... ((at_firstname.value LIKE 'TEST') OR (at_lastname.value LIKE 'TEST') OR (e.email LIKE '%TEST%') OR (at_phone.value LIKE '%TEST%')) 结尾。到底出了什么问题?
  • @clockworkgeek 我使用了 ->getSelect() 方法来显示“Select” sql 查询,一切看起来都很正常。我有 2 个客户:Ion 和 Daniel。当我使用脚本时,它的行为就像他只在“Ion”客户而不是“Daniel”中搜索。所有结果都显示为“Ion”客户。

标签: magento magento-1.8


【解决方案1】:

试试这个,它 100% 为我工作

public function customerSearch($data) {
        $customerFactory = $this->_objectManager->get('\Magento\Customer\Model\CustomerFactory');
        $collection = $customerFactory->create()->getCollection()
                ->addAttributeToSelect("*")
                ->addAttributeToFilter('sponsor_id', array('eq' => $this->_customerSession->getCustomer()->getId()))
                ->addAttributeToFilter(
                        array(
                            array('attribute' => 'firstname', 'like' => '%' . $data . '%'),
                            array('attribute' => 'lastname', 'like' => '%' . $data . '%')
                        ))->load();
        $customer = $collection->getData();
        echo json_encode($customer);
        exit;
    }

其中,sponsor_id 是我的客户自定义属性,$data 是通过名字或姓氏查找客户的简单字符串。我希望这能解决您的问题。 谢谢

【讨论】:

    【解决方案2】:

    这次我的愚蠢超过了我。我在查询中使用了另一个属性,即 Magento 在过滤时遇到了一些问题,这是一个使用模块创建的自定义属性。感谢@clockworkgeek 对我的支持。

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2014-04-24
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多