Magento 2 – How to Retrieve Custom Table Data

databasemagento2

I have created a new table using custom module and stored value to this table, now, i need to get table data in block php file from database in magento 2, How to achieve this?

TableName="email_format" columns="customerid" and "format" now, i need to retrieve customer id and format value from table.

Thanks,

Best Answer

1) I Assume you have created Model and Collection file associated with that tables.

2) In a Block PHP file constructor add one argument (Dependency Injection) like below and store it in a class member variable.

 public function __construct(
    Context $context,
    \Namespace\Modulename\Model\ModelNameFactory $modelNameFactory,

    array $data = array()
) {
    $this->_modelFactory = $modelFactory;
    parent::__construct($context, $data);
}

3) Prepare a public method in your block to access collection like below.

public function getCollection(){

    return $this->_modelFactory->create()->getCollection();

}

4) Loop through each of the collection result.

Hope, this will help you.