Answer the question
In order to leave comments, you need to log in
How to populate a database table in symfony?
Suppose one of the tables should have default data, such as a list of object properties. Do I need to use migrations to populate a database table? Raw SQL query?
PS Symfony 5
Answer the question
In order to leave comments, you need to log in
You need to use fixtures: https://symfony.com/doc/master/bundles/DoctrineFix...
Usually, if necessary, I use migrations to fill in the database, where I write queries in pure SQL. You should not call the EntityManager and even more so drag the entire container into the migration, as mentioned above - this is a bad practice.
Fixtures, as already written here, are a test history, although no one forbids you from using them.
For the structure of the user migration, for its some initial filling - fixtures
There is such an option:
In some cases you might need access to the container to ensure the proper update of your data structure. This could be necessary to update relations with some specific logic or to create new entities.
Therefore you can just implement the ContainerAwareInterface with its needed methods to get full access to the container or ContainerAwareTrait.
// ... use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; class Version20130326212938 extends AbstractMigration implements ContainerAwareInterface { private $container; public function setContainer(ContainerInterface $container = null) { $this->container = $container; } public function up(Schema $schema) { // ... migration content } public function postUp(Schema $schema) { $converter = $this->container->get('my_service.convert_data_to'); // ... convert the data from markdown to html for instance } }
// ... use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerAwareTrait; class Version20130326212938 extends AbstractMigration implements ContainerAwareInterface { use ContainerAwareTrait; public function up(Schema $schema) { // ... migration content } public function postUp(Schema $schema) { $converter = $this->container->get('my_service.convert_data_to'); // ... convert the data from markdown to html for instance } }
// ...
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
class Version20130326212938 extends AbstractMigration implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function up(Schema $schema)
{
// ... migration content
}
public function postUp(Schema $schema)
{
$em = $this->container->get('doctrine.orm.entity_manager');
// ... update the entities
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question