Skip to content

How I can create a Model and Save it using Magento2?

I made a seeder custom command in order to populate multiple models for my developemtn easyness:

<?php

namespace MageGuideFirstModuleConsoleCommand;

use MageGuideFirstModuleModelBlogPost;
use MageGuideFirstModuleModelResourceModelBlogPostResource;
use SymfonyComponentConsoleCommandCommand;

use SymfonyComponentConsoleHelperProgressBar;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;

/**
 * Seed Multiple Blogposts with Skus
 */
class BlogpostSeeder extends Command
{
    const BLOGPOSTS_NUM=10000;

    private BlogPostResource $resource;

    public function __construct(BlogPostResource $resource){
        $this->resource=$resource;
        parent::__construct('db:seed:blogposts');
    }

    protected function configure(): void
    {
        $this->setDescription('Seed Multiple Blogposts in DB');
        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $progressBar = new ProgressBar($output, self::BLOGPOSTS_NUM);

        for($i=self::BLOGPOSTS_NUM;$i>0;$i--){
            $blogPost = new BlogPost();
            $blogPost->setTitle("BLogpost ".microtime());
            $blogPost->setBody("BLogpost Body".microtime());
            $this->resource->save($blogPost);
            $progressBar->advance();
        }
        return 0;
    }
}

But I need to populate extra stuff at BlogPost Model in my component. So how I can create a new model instance in my Command so I can populate my DB with blogposts?