Magento – Magento 2 Get table name with prefix

prefixtable

I'm trying to get a table name with prefix.

I currently try to use getConnection()->getTableName() but that doesn't work.

I've seen people suggesting to use $this->_resource->getTableName() but they don't say what $this refers to…

My class is this

class InstallSchema implements \Magento\Framework\Setup\InstallSchemaInterface 
{
    public function install(
        \Magento\Framework\Setup\SchemaSetupInterface $setup,
        \Magento\Framework\Setup\ModuleContextInterface $context
    ){
        $installer = $setup;
        $installer->startSetup();

        foreach (['sales_order_address', 'quote_address'] as $tableAlias) {
            $installer->getConnection()
                ->addColumn($installer->getConnection()->getTableName($tableAlias),
                    'shipping_ups_pickup_id',
                    [
                        'type'      => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                        'nullable'  => true,
                        'length'    => 40,
                        'default'   => null,
                    ]
                );
            $installer->getConnection()
                ->addColumn($installer->getConnection()->getTableName($tableAlias),
                    'shipping_additional_information',
                    [
                        'type'      => \Magento\Framework\DB\Ddl\Table::TYPE_TEXT,
                        'nullable'  => true,
                        'default'   => null,
                    ]
                );
        }
        $installer->endSetup();
    }
}

Best Answer

Here is a snippet from https://github.com/magento/magento2/blob/2.2-develop/app/code/Magento/Cms/Setup/InstallSchema.php

Just a random InstallSchema file. As you can see getTable method is called on $installer which is a class implementing SchemaSetupInterface

/**
 * Create table 'cms_page'
 */
$table = $installer->getConnection()->newTable($installer->getTable('cms_page')
...

As you can see you should not not call getTable on Connection object.

Related Topic