Doctrine2 entity with varchar id don't insert id into database

Asked
Active3 hr before
Viewed126 times

5 Answers

entity
90%

Doctrine handles the @ORM\GeneratedValue(strategy="Identity") differntly for each database. In case of MySql it is will insert a generated value also known as AUTO_INCREMENT resulting in integer as ID. Please take a look at http://docs.doctrine-project.org/en/2.0.x/reference/basic-mapping.html#identifiers-primary-keys.,As you mentioned you would like to set the ID by the input of your form. But let me point out that the user can put in duplicates primary keys. In order to catch it you have to check if an object already exists and in that case I would recommend use \DoctrineModule\Validator\NoObjectExists. See https://github.com/doctrine/DoctrineModule/blob/master/docs/validator.md about Doctrine validators., of course. it add new row but with id set to null :( there are many more columns which are inserted. it was empty table so any new insert throw an exception that there is id with null value. – RoaK Jul 18 '14 at 14:32 ,In your case you shouldn't be using the GeneratedValue annotation including it's strategy. So completely remove it. If you want the ID of your form you could setup a constructor in your entity which will set your ID for that entity.

In your case you shouldn't be using the GeneratedValue annotation including it's strategy. So completely remove it. If you want the ID of your form you could setup a constructor in your entity which will set your ID for that entity.

class Checkpoints {

   public
   function __constructor($id) {
      $this - > id = $id;
   }

   /**
    * @var string
    *
    * @ORM\Column(name="id", type="string", length=15, nullable=false)
    * @ORM\Id
    */
   private $id;
   // rest of the entity...
}

So in your controller you will probaly use something like this

if ($form - > isValid() {
      $formData = $form - > getData();
      $checkpoint = new Checkpoints($formData['id']);
   }

So in order to check if an object exists with the ID you can add this validator to your inputfilter of your form:

public
function getInputFilterSpecification() {
   $entityManager = $this - > serviceManager - > get('Doctrine\ORM\EntityManager');

   return array(
      'id' => array(
         'validators' => array(
            array(
               'name' => 'DoctrineModule\Validator\NoObjectExists',
               'options' => array(
                  'object_repository' => $entityManager - > getRepository('Application\Entity\Checkpoints'),
                  'fields' => 'id'
               )
            )
         )
      )
   );
}
load more v
88%

Advanced field value conversion using custom mapping typesThe entityThe mapping typeExample usage,Doctrine Mapping Types,Why does Doctrine not create proxy objects for my inheritance hierarchy?,SecurityUser input and Doctrine ORMPreventing Mass Assignment Vulnerabilities

Related to the previous limitation with Foreign Keys as Identifier you might be interested in mapping the same table structure as given above to an array. However this is not yet possible either. See the following example:

1 CREATE TABLE product(
   id INTEGER,
   name VARCHAR,
   PRIMARY KEY(id)
);

CREATE TABLE product_attributes(
   product_id INTEGER,
   attribute_name VARCHAR,
   attribute_value VARCHAR,
   PRIMARY KEY(product_id, attribute_name)
);
2
3
4
5
6
7
8
9
10
11
12

This schema should be mapped to a Product Entity as follows:

1 class Product {
   private $id;
   private $name;
   private $attributes = array();
}
2
3
4
5
6
load more v
72%

How to Generate Entities from an Existing Database ,When starting work on a brand new project that uses a database, two different situations comes naturally. In most cases, the database model is designed and built from scratch. Sometimes, however, you'll start with an existing and probably unchangeable database model. Fortunately, Doctrine comes with a bunch of tools to help generate model classes from your existing database.,The first step towards building entity classes from an existing database is to ask Doctrine to introspect the database and generate the corresponding metadata files. Metadata files describe the entity class to generate based on table fields.,This command line tool asks Doctrine to introspect the database and generate new PHP classes with annotation metadata into src/Entity. This generates two files: BlogPost.php and BlogComment.php.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CREATE TABLE `blog_post`(
   `id`
   bigint(20) NOT NULL AUTO_INCREMENT,
   `title`
   varchar(100) COLLATE utf8_unicode_ci NOT NULL,
   `content`
   longtext COLLATE utf8_unicode_ci NOT NULL,
   `created_at`
   datetime NOT NULL,
   PRIMARY KEY(`id`)
) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;

CREATE TABLE `blog_comment`(
   `id`
   bigint(20) NOT NULL AUTO_INCREMENT,
   `post_id`
   bigint(20) NOT NULL,
   `author`
   varchar(20) COLLATE utf8_unicode_ci NOT NULL,
   `content`
   longtext COLLATE utf8_unicode_ci NOT NULL,
   `created_at`
   datetime NOT NULL,
   PRIMARY KEY(`id`),
   KEY `blog_comment_post_id_idx`(`post_id`),
   CONSTRAINT `blog_post_id`
   FOREIGN KEY(`post_id`) REFERENCES `blog_post`(`id`) ON DELETE CASCADE
) ENGINE = InnoDB AUTO_INCREMENT = 1 DEFAULT CHARSET = utf8 COLLATE = utf8_unicode_ci;
load more v
65%

References to related entities are only possible in the WHERE clause and using sub-selects.,First notice that the generated SQL to create the tables for these entities looks like the following:,The constants for the different hydration modes are:,If we check the generated SQL you will notice it has some special conditions added to ensure that we will only get back Employee entities:

< ? php
$query = $em - > createQuery('SELECT u FROM MyProject\Model\User u WHERE u.age > 20');
$users = $query - > getResult();
load more v
75%

Both ORMs support behaviors. Behaviors can be used to modify your classes during the build process.They can add attributes and methods to model classes, modify the structure of a database by adding columns or tables.,The sluggable behavior builds the slug (URL friendly version of post title) of predefined fields.,set a maximum size for the file in bytes,The sluggable behavior allows a model to offer a human readable identifier. In the schema.xml in the table definition add the tag . A unique slug is automatically composed for every object that you save. It can be used to provide user-friendly URLs.

load more v

Other "entity-undefined" queries related to "Doctrine2 entity with varchar id don't insert id into database"