In this post, we will create Model and Collection of a module in Magento 2. After this post, you can use Models for saving data and can get table collections.

 

1. You need to create a simple module, after that you can follow this post.

2. We need to create these files to insert, update, delete and get data in the database.

Softprodigy is company Namespace and Mcomingsoon is the module Name.

Frontend Routes Name is coming soon

1   - Create model file: app/code/Softprodigy/Mcomingsoon/Model/Cbackground .php and  insert this following code into it:

namespace Softprodigy\Mcomingsoon\Model;
use Magento\Framework\Model\AbstractModel;
class Cbackground extends AbstractModel
{
	public function _construct() {
       	 $this->_init('Softprodigy\Mcomingsoon\Model\Resource\Cbackground');
    }     
}

2 - Create resource model file: app/code/Softprodigy/Mcomingsoon/Model/Resource/Cbackground .php and insert this following code into it:

namespace Softprodigy\Mcomingsoon\Model\Resource;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Cbackground extends  AbstractDb
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
	/* Custom Table Name */
         $this->_init('sps_comingsoon_background','id');
    }
}

 3 - Create collection file: app/code/Softprodigy/Mcomingsoon/Model/Resource/Cbackground/ Collection.php and insert this following code into it:

	namespace Softprodigy\Mcomingsoon\Model\Resource\Cbackground;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
class Collection extends AbstractCollection
{
    protected function _construct()
    {
        $this->_init('Softprodigy\Mcomingsoon\Model\Cbackground', 'Softprodigy\Mcomingsoon\Model\Resource\Cbackground');
    }
}

 4. - Create controller file: app/code/Softprodigy/Mcomingsoon/Controller/Index/Index.php and insert this following code into it:

	namespace Softprodigy\Mcomingsoon\Controller\Index;
  class Index extends \Magento\Framework\App\Action\Action {

    /** @var \Magento\Framework\View\Result\PageFactory  */
        protected $resultPageFactory;
	 
    public function __construct(
    \Magento\Framework\App\Action\Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory 
    ) {
			$this->resultPageFactory = $resultPageFactory;
			parent::__construct($context);
                       
            
    }
 public function execute() {
	 $model = $this->_objectManager->create('Softprodigy\Mcomingsoon\Model\Cbackground');		 
         $test =  $model->load(1);         var_dump($test->getCollection()->getData());                                                                                                                    die("Hello");
    }
}