1

I am trying to get table prefix by using the function getTableName(), But couldn't get the result, Below is my code,

$sum = new \Zend_Db_Expr('(SUM(`main_table`.`product_id`)/`main_table`.`product_id`)');
    $collection = $this->orderItem->getCollection()
        ->addFieldToSelect(['product_id', 'frequency' => $sum])
        ->removeFieldFromSelect('item_id');
    $select = $collection->getSelect();
    $connection = $collection->getConnection();
    $orderItemTable = $connection->getTableName('sales_order_item');

    $select->joinLeft(
        ['sub_table' => $orderItemTable],
        '`main_table`.`order_id` = `sub_table`.`order_id` AND `main_table`.`product_id` != `sub_table`.`product_id`',
        ['product_id']
    );
    $collection
        ->addFieldToFilter('main_table.product_id', ['eq' => $productId])
        ->addFieldToFilter('sub_table.product_type', ['nin' => $restrictedProductTypes])
        ->addFieldToFilter('sub_table.parent_item_id', ['null' => true])
        ->setOrder('frequency');
    $select->group('sub_table.product_id');
    $result = $connection->fetchAll($select);

I just tried the below code, but it forced me to set area code

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);    
$obj = $bootstrap->getObjectManager();
$deploymentConfig = $obj->get('Magento\Framework\App\DeploymentConfig');
var_dump($deploymentConfig->get('db/table_prefix'));
0
/**
 * @var \Magento\Framework\App\DeploymentConfig
 */
protected $deploymentConfig;
public function __construct(
    \Magento\Framework\App\DeploymentConfig $deploymentConfig
)
{
     $this->deploymentConfig = $deploymentConfig;
}
 protected function collectNewDataForProduct($productId)
{
    $orderItemTable = $this->deploymentConfig->get('db/table_prefix') . $connection->getTableName('sales_order_item');
}
0

You can also try with below method to get table prefix name,

protected $_resource;
public function __construct(       
    \Magento\Framework\App\ResourceConnection $resource
) {
    $this->_resource = $resource;
}

public function getTable($tablename)
{
    return $this->_resource->getTableName($tablename);
}
4
  • But this doesn't work for me. Nov 15 '16 at 10:04
  • Have you passed $tablename as sales_order_item Nov 15 '16 at 10:05
  • yes I just tried , $this->_resource->getTableName('sales_order_item'); Nov 15 '16 at 10:08
  • Have you remove var folder? Now check i have replace protected to public Nov 15 '16 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.