I have below sql query, how do I turn this to Magento get data method to retrieve data?

magento.stackexchange https://magento.stackexchange.com/questions/328419

  •  15-04-2021
  •  | 
  •  

Вопрос

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;
}
Это было полезно?

Решение

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.

Другие советы

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;

}

Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top