Question

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;
}
Was it helpful?

Solution

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.

OTHER TIPS

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

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;

}

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top