0

I have below sql query, how do I turn this to Magento get data method (collection?) to retrieve data (not using ObjectManager)? Please help.

public function  getNewCustomer()
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();
    $query = "SELECT entity_id FROM customer_entity WHERE created_at >=  (NOW() - INTERVAL 10 DAY);";
    $result = $connection->fetchAll($query); 
    
    return $result;
}
0
1

Try this

protected $_customerFactory;

public function __construct(
    ....................................
    \Magento\Customer\Model\CustomerFactory $customerFactory,
    ....................................
)
{
    ....................................
    $this->_customerFactory = $customerFactory;
    ....................................
}


public function getNewCustomers()
{
    $customerData = $this->_customerFactory->create()->getCollection();
    $customerData->addAttributeToSelect("*");

    $currtDate = date("Y-m-d H:i:s"); // Y-m-d h:i:s
    $newDate = strtotime('-10 day', strtotime($currtDate));
    $newDate = date('Y-m-d H:i:s', $newDate);

    $customerData->addFieldToFilter('created_at', ['gteq' => $newDate]);
    $customerData->addFieldToFilter('created_at', ['lteq' => $currtDate]);

    $customerData->load();

    return $customerData;
}

I Hope This Helps You.

1
  • thanks...I did try few times, .but looks like something wrong with the query,
    – Paul Fan
    Dec 23 '20 at 7:38
0

You can use below code and update based on your requirement to get customer collection

class MyClass 
{
    protected $_customer;
    protected $_customerFactory;

    public function __construct(\Magento\Customer\Model\CustomerFactory $customerFactory
    )
    {

        $this->_customerFactory = $customerFactory;
    }

  

    public function getFilteredCustomerCollection() {
        return $this->_customerFactory->create()->getCollection()
                ->addAttributeToSelect("*")
                ->addAttributeToFilter("created_at", array("geq" => "(NOW() - INTERVAL 10 DAY)"))
                -load();
    }
}

I hope this will help you.

Thanks

0

public function getNewCustomer() { $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $resource = $objectManager->get('Magento\Framework\App\ResourceConnection'); $connection = $resource->getConnection(); $query = "SELECT entity_id FROM customer_entity WHERE created_at >= (NOW() - INTERVAL 10 DAY);"; $result = $connection->fetchAll($query);

return $result;

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.