1

I'm creating my first web app with Symfony. Now I found a solution for making my code more customizable and extensible. But for making this solution working in my app I need some help.

Is it possible in Symfony to insert data that is in a key -> value array to a table in the database?

For example, I have an array that looks like: array('Titel' => 'The Hobbit', 'Music' => 'Add Sheeron')

Now I need to put this into the database table X that looks like: Titel (varchar (255)) Music (varchar (255))

How can I insert the array into the database? Also the array can contain data that need to be inserted into another table with other Key names.

In other words, how can I map the array key to a field in the database so that I can use it to insert it into the table?

2 Answers 2

2

Okay let's say your array is called $music. and it looks something like this:

$music = array('Titel' => 'The Hobbit', 'Music' => 'Add Sheeron');

Now you need to create a new instance of your entity which maps to the respective table in your database. For this you need to create a new entity and then persist and flush it.

$em = $this->container->get('doctrine.orm.entity_manager');
$music = array('Titel' => 'The Hobbit', 'Music' => 'Add Sheeron');
$entityMusic = new MusicEntity(); //This is your entity
$entityMusic->setTitel($music['title']); //Respective entity methods
$entityMusic->setMusic($music['Music']);
$em->persist($entityMusic);
$em->flush();

If you have more than one values you want to insert, you can run a basic for loop to insert all values you want.

For the second part of your question, you will have to look into Relationship and Mapping of Entities. Documentation here

Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible to insert data without using the setters of the entity? In normal PHP code it looks something like: "INSERT INTO $tableName ($columns) VALUES ($values)"; $columns is in this case array('Titel', 'Music') and $values array('The Hobbit', 'Add Sheeron').
You can probably use a native query for that. However it will defeat the purpose of using a framework.
Ok that was I afraid for. Then It would be using the insert statement of a regular sql.
That is correct. which is equivalent to writing core PHP
You can create your Entity and use Serializer component too. docs
0

As I know there is no existing method do to this.

If you want to have auto-binding data you need to use Symfony forms. There is also best practices for forms.

And if you don't want to use forms you need to bind every field manualy.

1 Comment

The OP has not mentioned that forms are being used in the problem. Your answer does not make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.