Search code examples
postgresqlsymfonypomm

Pommbundle Custom query Insert or update - Symfony2


I would like to create a custom insert or update with pommbundle but in the documentation i have just for a select query.

It's possible to give me a simple example with a possibility to have a last insert id? with ... currval ou lastval?


Solution

  • There are several ways of inserting data in the database using PommBundle.

    If you do not use the Model Manager and you want to perform a custom insertion:

    // in the controller
    $this->get('pomm')
        ->getDefaultSession()
        ->getQueryManager()
        ->query('INSERT INTO … VALUES ($*::text, $*::int4…)', [$param1, $param2]);
    

    This method is tedious because you have to specify all the fields by hand, it may break if the schema changes but you can specify a complex insertion query using SQL acrobatics.

    If the goal is just to save a model, the model manager eases the insertion of data using entities:

    use Path\To\Model\MyDb\MySchema\MyEntityModel;
    
    // …
    $entity = $this->get('pomm')
        ->getDefaultSession()
        ->getModel(MyEntityModel::class)
        ->createAndSave(['field1' => $param1, …]);
    

    The returned entity is the image of the inserted data with the database default values (most of the time auto generated primary key).

    Here is the documentation about it.