Direct SQL Query in Magento 2

There are many situations where executing direct raw SQL queries would be simple and much quicker leading to a more optimized Magento get collection query as a performance basis.

On a large data set of an entity, Saving each individual entity can take a long time with resource-hungry and therefore make the system unusable.

Overcome this issue it is possible to issue a direct SQL query that could update a large set of data of an entity in fewer seconds.

When you use Direct SQL Query you don’t need to worry about Model/Factory Pattern. Continue reading “Direct SQL Query in Magento 2”

How to get table name with prefix in Magento 2?

You can fetch prefix values from the table name in Magento 2. If your database table has set prefix value for all the tables and wants to fetch that value you can read the next portion.

Let’s say, You have added Prefix value as mage_ for all the tables.

Using getTableName() method, you can get a table with prefix code always,

<?php
namespace Your\PathTo\Model;

use Magento\Framework\App\ResourceConnection;

class PrefixTable
{

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

   public function getPrefixTable()
   {
    /* Create Connection */
        $connection  = $this->resource->getConnection();
        $tableName   = $connection->getTableName('sales_order'); // return "prefix_sales_order"

    /* Run Row query */
        $query = "SQL Query";
        $connection->query($query);
    }
}

In the above function, your table will get a prefix value with the table name.
If your table has a prefix as mage_ then your table value will get like, mage_sales_order

How to Convert CMS page content to html interpretation in Magento 2?

We can convert CMS page content into HTML specific format using native Magento class.

We need to use, \Magento\Cms\Model\Template\FilterProvider class to filter page content in the template file.
In PHP file,

<?php
public function __construct(
    \Magento\Cms\Model\Template\FilterProvider $filter
) {
    $this->filter = $filter;
}
/*
* Page content $content
*/
public function getContentFromPage($content)
{
    return $this->filter->getPageFilter()->filter($content);
}

Call from template file,

$content = "YOUR_CMS_PAGE_CONTENT";
echo $this->getContentFromPage($content);