Question

Is it possible to get a list of the table columns that are related to a model ?

Was it helpful?

Solution

It is possible to use the describeTable() method.

So your resource model, you can create a function as the following one, this will return an array of fields for the main table:

public function getFields()
{
    $fields = $this->_getWriteAdapter()->describeTable($this->getMainTable());
    return $fields;
}

OTHER TIPS

For who are struggling with this in Magento 2:

In your custom resource model class, add this function:

public function getFields()
{
    $fields = $this->getConnection()->describeTable($this->getMainTable());
    return $fields;
}

And in somewhere you need to get all columns of a table (all fields of object):

$objectModel = $this->objectFactory->create(); // I prefer using dependency injection
$keys = array_keys($objectModel->getResource()->getFields());

P/S: Thank you @Fra for a great self-answer question. It saved a lot of my time.

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