Create a model factory for your BlogPost model. This should be located in your module and might look like this:
// app/code/MageGuide/FirstModule/Model/BlogPostFactory.php
<?php
namespace MageGuide\FirstModule\Model;
use Magento\Framework\ObjectManagerInterface;
class BlogPostFactory
{
private $objectManager;
public function __construct(ObjectManagerInterface $objectManager)
{
$this->objectManager = $objectManager;
}
public function create()
{
return $this->objectManager->create(BlogPost::class);
}
}
Modify your command to accept the BlogPostFactory via dependency injection:
// app/code/MageGuide/FirstModule/Console/Command/BlogpostSeeder.php
// ...
use MageGuide\FirstModule\Model\BlogPostFactory;
// ...
class BlogpostSeeder extends Command
{
// ...
private BlogPostFactory $blogPostFactory;
public function __construct(BlogPostResource $resource, BlogPostFactory $blogPostFactory)
{
$this->resource = $resource;
$this->blogPostFactory = $blogPostFactory;
parent::__construct('db:seed:blogposts');
}
// ...
protected function execute(InputInterface $input, OutputInterface $output): int
{
$progressBar = new ProgressBar($output, self::BLOGPOSTS_NUM);
for ($i = self::BLOGPOSTS_NUM; $i > 0; $i--) {
$blogPost = $this->blogPostFactory->create();
$blogPost->setTitle("Blogpost " . microtime());
$blogPost->setBody("Blogpost Body" . microtime());
// Set additional data here if needed
$this->resource->save($blogPost);
$progressBar->advance();
}
return 0;
}
// ...
}
With these changes, you can now create and populate instances of the BlogPost model using the factory, and you have the flexibility to set additional data as needed before saving them to the database.