Magento2 : Model , ResourceModel , Collection

Before Creating Model visit  Magento2 structure Admin Module in Magento2 
Create File Inside Model: The template is the class that will allow you to interact easily with your database. This class should not contain any SQL directly. This model class extends AbstractModel class.The _construct() will call ResourceModel class.

namespace NameSpace\ModuleName\Model;
use Magento\Framework\Model\AbstractModel;

class ModelName extends AbstractModel
{
    /**
     * Define resource model
     */
    protected function _construct() 
    {
        $this->_init('NameSpace\ModuleName\Model\ResourceModel\ModelName');
    }
   
   // Call Function from Model to Resource Model   
   public function callResourceModelFunction
   {
     $this->getResource()->ResourceModelFunctionName();
   } 

   // Call Function from Model to Resource Model collection
   public function callResourceModelCollectionFunction
   {
     $this->getResourceCollection()->ResourceModelCollectionFunctionName();
   }  

}
Create file inside ResourceModel :
The resource model is the class that allows you to "store" your SQL queries, it is used by the model to interract in SQL with the database. The _construct() will use table_name and its primary id.
namespace NameSpace\ModuleName\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use \Magento\Framework\Model\ResourceModel\Db\Context;
class ModelName extends AbstractDb 
{ 
    /**
     * Define main table
     */
    protected function _construct() 
    {
        $this->_init('table_name', 'entity_id');
    } 
    
    public function __construct(
    Context $context, $connectionName = null
    ) {
        parent::__construct($context, $connectionName);
    }
  
    public function doSomeAction()
    {
      $connection = $this->getConnection(); // $connection object is responsible to excute query
    }
 
}
Create file inside ResourceModel => ModelName  => Collection.php
namespace NameSpace\ModuleName\Model\ResourceModel\ModelName;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection 
{
    protected $_idFieldName = 'entity_id';
    
    /**
     * Define model & resource model
     * Give all object of same table.  
     */
    protected function _construct() 
    {
        $this->_init(
                'NameSpace\ModuleName\Model\ModelName',
                'NameSpace\ModuleName\Model\ResourceModel\ModelName'
        );
        
        $this->_map['fields']['entity_id'] = 'main_table.entity_id';
    }
    
    protected function _initSelect() {
        parent::_initSelect();
        // Join with other table return collection ...
        // $this->getSelect()->joinLeft();
        return $this;
    }
}

Comments