How to add column in sales_order table using db_schema.xml Magento 2?

You can add a new column in sales_order table using db_schema.xml under your module etc folder from Magento 2.3 and Upper version.

We try to add a new column called order_country in sales_order table.

To add order_country field in sales_order table, you need to only add one row inside the db_schema.xml file structure.

Here, the Main table for Sales Operation is sales_order and you can add a new field in sales_order table by the below way, Continue reading “How to add column in sales_order table using db_schema.xml Magento 2?”

Get Auto Increment Field from a table using Magento 2.

You can get the Auto Increment Field from a database table using Magento 2 as Best coding practice way.

You need to use getAutoIncrementField() for getting the auto-increment field from the table.

Output: Returns field name if an auto-increment field is available otherwise return as false.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class AutoIncrementField {

    const ORDER_TABLE = 'sales_order';

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

    public function __construct(
       ResourceConnection $resourceConnection
    ) {
       $this->resourceConnection = $resourceConnection;
    }

    /**
    * get AutoIncremntFieldName using Query
    *
    * @return string|bool
    */
    public function getAutoIncremntFieldName()
    {
      $connection  = $this->resourceConnection->getConnection();
      $tableName = $connection->getTableName(self::ORDER_TABLE);
      $getFieldName = $connection->getAutoIncrementField($tableName);

      return $getFieldName;
    }
}

You can call $this->getAutoIncremntFieldName() function to check sales_order table with auto_increment field name.

Output:
entity_id

Check if database table exists or not using Magento 2.

Magento 2, When you deal with database table related stuff and first you want to check if a specific table exists or not in the database.

You need to use isTableExists() for getting table exists or not. using the above function you get the idea of table available or not.

Output: isTableExists() returns always boolean. true or false. Continue reading “Check if database table exists or not using Magento 2.”