Book Image

Magento 2 Development Cookbook

Book Image

Magento 2 Development Cookbook

Overview of this book

With the challenges of growing an online business, Magento 2 is an open source e-commerce platform with innumerable functionalities that gives you the freedom to make on-the-fly decisions. It allows you to customize multiple levels of security permissions and enhance the look and feel of your website, and thus gives you a personalized experience in promoting your business.
Table of Contents (18 chapters)
Magento 2 Development Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a flat table with models


When you want to save data in a module, you may want to store that in a custom entity. That entity needs a database table and a model that talks with that database table.

We will create a subscriptions entity where we can store subscriptions.

Getting ready

In this recipe, we will extend the module of Chapter 4, Creating a Module, with an entity with a database table. Make sure you have the starter files for this recipe installed.

How to do it...

In the next steps, we will learn how we can add entities to an existing module:

  1. When installing a new entity, we have to create a resource model. We can do this by creating the file app/code/Packt/HelloWorld/Model/ResourceModel/Subscription.php with the following content:

    <?php
    namespace Packt\HelloWorld\Model\ResourceModel;
    
    class Subscription extends \Magento\Framework\Model\ResourceModel\Db\AbstractDb {
      public function _construct() {
        $this->_init('packt_helloworld_subscription', 'subscription_id');
      }
    }
  2. The...