Completion requirements
Model triad
Let's add some information to the database and display it on the storefront.For example, we need to implement a simple blog module.So, we need to have some records in the database and for that we need to create a database table in Magento, add some data in it and display that information on the storefront.Let's first add a database table to Magento.We have several options here.The most correct of them is the declarative scheme.Let's look at an exampleFor example, in vendor magentomodule catalogE T Cdb schema dot xmlAs you can see, the declarative schema is quite simple.The declarative schema defines what the structure of the database should be.And Magento detects the differences between the current table structure and what it should be.A table node can contain the following attributes: name, resource, engine, and comment.So the name is actually the name of the table. "resource" is actually the "Shard" of the database on which the table is installed.this could be "default", "checkout" or "sale".But if you only have one database and a small project, let's just use "default" here. "engine" could be something like "Inno db" or "memory", and "comment".A table node can contain three types of subnodes."column", "constraint" and "index". The column subnode defines a column in the table.Each column requires its own declaration.A column can have the following attributes."Type" - This can be a boolean, date, datetime, decimal, float, JSON, text, etc. The full list can be found in the official Magento documentation.The "name" of this column and additional attributes such as "default" initialize the column to the specified default value.Disabled.It disables or removes a declared table column constraint or index."identity" specifies whether the column is auto-incrementing, "length" actually specifies the length of the column, can be used for "char" or "varchar" columns.Like here. The new label indicates whether the column is nullable.In the onCreate attribute we can add some trigger. "Padding" is the size of the integer column. "precision" is the number of digits allowed in the "real" data type.The scaling of the number of digits after the decimal point in the real and unsigned or numeric data types determines whether the call can contain positive and negative values.Overall, it's pretty simple if you understand the basics of the MySQL database.Let's add our own database table.Let's copy and paste this example into the existing TestNamespace TestModuleName in the E T C folder.okAnd let's remove all the unnecessary information here.Let's leave one column, just for example.Let's define our database table, let's call it "test table".okresource is default, engine is innoDb and "comment" of this database table will be "Test blog table"Let's leave the entity_id column.Let's add a few moreLet's add a "varchar" columnlet's call it "title"We have two more unnecessary attributes here.Let's add length.For example, 64 symbols.And let's change the commentok.And let's add another text column, call it "content". And remove the unnecessary "length" from here.Let's change the comment - "Content".ok.You can also add createdAt and updatedAt columns here.As you can see, the first column is a timestamp, the name of this column is created_at.The default value for this column is the current timestamp.Same goes for update time, the only difference is that this column will be updated automatically every time we update this table.Let's add some primary index to this table.Let's add entity idAs a result, we have a new table named test_table, which contains the following columnsentity id, title, content, created at and updated at.Let's run setup upgrade command to see this table in the database.Ok, let's check the database.if we update the list of tables.We will see our new database table.Now we can add some data to this table.For this we can use data patches.Let's take another example from the module-catalog module.It should be located in the Setup Patch folder.Let's check the data. For example, this one.A data patch is a class that contains instructions for modifying data.Unlike the declarative schema approach, the fixes will only be applied once.The list of applied patches is stored in the patch list database table, and the applied patch will be applied when the setup upgrade shell command is run.Now we can add some custom code to the apply method.Let's add this patch to our module.It should be located in the Setup/Patch/Data folder.Let's change the name of this patch.We can remove the unnecessary code from here and add our code here.Again, the patch must implement Data Patch Interface and must be located in the Setup Patch Data folderIn this case, everything in the apply() method will be applied only once.And then this information will be stored in the patch_list database table.For example, we need to initialize some data in our test table.For this we can add the following code. So it should bemodule, Data, Setupget Connectionstart SetupAnd if you look at this method, you'll see that there are some additional SQL queries here.So this is not really a required step, but it is usually better to add startSetup() and endSetup() statements here.Inside these instructions we can add our own code.then we can add this information to the databaseLet's getConnection() and insertArray()We need to specify the table name.We need to specify a list of columns.And, actually, the data.And that's all.After running the setup:upgrade script, this information will be added to our test table in the database.Also keep in mind that we will have to change the namespace.TestNameSpace TestModuleName okAnd now we can run the setup upgrade commandWe have some information in the database, so to create and change the structure of the database,we will have to use the declarative schema.To make changes, we can use data patches.We can also use schema corrections.Schema patches are used in conjunction with declarative schema, but these patches allow complex operations such as adding triggers, stored procedures, functions, etc.In the real world we don't need them.But in previous versions of Magento, you can still see the old approach with installation and update scripts, as well as in some third-party modules.Let's take a quick look at them.Before Magento 2.3, extension developers had to write code to change the database schema, and before Magento 2.3, the following types of scripts existed: InstallData and InstallSchema scripts, which are executed when a model is first installed.Incremental scripts UpgradeData and UpgradeSchema that extend the schema of an existing module.And recurring scripts that are executed every time Magento is installed or updated.And Uninstall to clean the database after removing this module. Each script iteratively adds changes during the installation process, update scripts apply only those changes that have not yet been applied.Let's take a look at this, as you can see, we have a comparison of versions here.We need to determine the version.From the module that can be found here - setup version.Here we need to define that only for this version of this module this script should be applied.InstallUpgrade scripts are deprecated and Magento recommends moving installUpgrade scripts to the declarative schema.Now we have a database table created using the declarative schema and some information added to the database by patch.And we need to access this information through code.To do this, we will have to use the Magento ORM system.Which consist of Models, Resource Models and Collections.Models are the data and behavior that represent entities. Resource models are the data mappers for the storage structure.and collections encapsulate sets of modules and their associated functionality, such as filtering, sorting, and pagination.ORM gives you the ability to create, load, update and delete data in the database.Let's create a blog model first.Let's add a model folder.Let's set up a blog model file.The Model class must extend AbstractModel.And in construct we need to mention the resource model.As you can see, we have mentioned the resource model here.We need to add the resource model to the resource model folder.In the resource model we need to specify the table name and the identifier field name.The table name is test_table.And the field name is entity_idAnd finally, Collection. It should be in the ResourceModel folder and the name of this file is Collection.It should extend AbstractCollection class and we need to specify the id field name and in the constructor we need to specify the model and resource model.And that's all.We have created a database table, a CRUD model, a resource model and a collection.But how to use them? Here we have to use factories. In Magento, the factory object method will be used to create an object instance, the class name factory is the model class name and the word factory is added.Let's say we need to use our blog model.For our example, we will have a Blog Factory class. You don't need to create this class, Magento will create it for you.Whenever the Magento object manager encounters a class name ending with world factory, it automatically generates a factory class in the generated folder if the class does not already exist.To create an instance of a Model object, we will use automatic constructor dependency injection to inject a factory object, and then use the factory object to create an instance of the Model object.For this, let's use our view model class.Let's try to get some information from the database.Let's add the dependency to the constructor first.This will be a collection class because we are going to get a list of records from the database so for that we will have to use collection and for collection we will also have to use factories.We need to inject the collection model class but with a factory keyword. Here.Let's take a look on it. Let's add TestModuleName Model ResourceModel Collectionok, but the postfix should be a factory word, let's call it CollectionFactoryLet's add fields here and remove unnecessary qualifiers.ok.Looks good to me. So now, as you can see, CollectionFactory class doesn't exist.To generate this, let's clear the generated folder.And let's clear the cache.Ok.Let's open some page on a storefront.ok.And let's check the generated folder.As you can see in Test Namespace, Test Module Name, Model, Resource Model, Collection Factory. Here it is.Magento has automatically generated a factory class for this model, so we can now use it.Let's say we can add another public method.Let's call it getBlogCollection()and let's return the collection FactoryBut this is Factory, we need to initialize this class.To do this we need to use the create method in the construct method.Now the proper collection class will be initialized here.Now we can use the blog collection in the template file.Let's do this.Let's move on to the template file.Let's get the information from the database, so let's remove the unnecessary code from here.As you can see, we can get this information from the view model object.Let's get a collection of blogs.Let's create a blogCollection variable.ok.Now we can use it.ok.Let check it on a storefront.Let's clear the cache.ok.Looks fine.But let's add a simple form here to be able to add new posts to database from the storefront.Let's clear the cache.Let's check itOKBut as you can see, we have mentioned the save action here.As you can see, we will use the same name and the same controller name, but a different action name.To do this, we can add another action to the Test controller folder. Let's call it Save.Let's remove unnecessary scripts from here.Let's add the necessary code to this action.First of all, we need to add to the constructorBlog model and resource model.For the blog model we will have to use factories, but the resource model can be used directly.Let's get the title from the request.Let's look at the content.Let's create a blog post object.For this we need to use Blog Factory.You can set some data.Let's save this information in the database.This is just a test scenario, so let's skip that part.As a result we have to redirect this action to the special_url_key test testAnd let's return the result.What do we have here?We have all the information from the request.As you can see, we are going to send two fields."Title" and "content" so we can get them here.We then used blogFactory to create a blog model.We then fill in the information about this object and then, using the blog resource model, save this new object. We could do something like blogPost save, but this is a deprecated approach and Magento recommends using blogResource directly for such purposes.Let's change this a little.Let's remove the unnecessary qualifier.Let's cleanup the generated folder.And clear the cache.Let's refresh this page.OK.Let's add some additional information.OK, works fine.But if we try to add another record here.You will not see any changes because this page is cached.To fix this, just for testing purposes, we can add the following attribute here, cacheable is false.And as a result, this page will work without cache.So we don't need to refresh the cache every time we need to see new data here.If we add another entryBlog Title is testBlog Content is TestWe will immediately see the information on the storefront.But in case we need dynamic data on the storefront, we will have to use a special JavaScript flow in Magento called private content or use a unique cache key because cacheable is false is not a best practice and Magento does not recommend this approach. Because if we use this approach this page will be generated every time any user requests it and the performance for this page will be extremely low.Let's leave things as is for now and add deletion links to our posts.Additionally, we need to add an ID to this URLok.Let's add some space after this line and check.Now we need to add the delete action class.First of all, we need to get the ID of our blog post.Next we need to create a blog post object.And now we can set this ID.Now we can delete this post from the database via the blogResource class.OK, we can do something like this.BlogPost delete, but as you can see, it's depricated and Magento recommends using the resource model.And service contracts instead of this method, but it is also possible to use this method. But it is also depricated.That's why we use this resource model here.So now we can check it out. But first let's clear the cache.OK.Let's refresh this page.Let's try using the delete button.OK, works fine.Now we can add and delete information in the database.Everything works fine.Let's look at the database.Here it is.Here's how it works.
You have completed 0% of the lesson
0%
© 2025 Termidy. All rights reserved. Privacy
Adobe, Magento and Adobe Commerce are trademarks of Adobe Inc. Termidy is an independent
preparation tool and is not affiliated with or endorsed by Adobe.
Contact us: admin@termidy.com