xangr
xangr

Reputation: 879

Doctrine2 strictly trying to inser t NULL when i use one-to-one and many-to-one relations

Places.yml

manyToOne:
  excursions:
    targetEntity: Excursions
    inversedBy: places
    inverse: true
    cascade: ["ALL"]
    nullable: false
    joinColumn:
      name: idx
      referencedColumnName: place_id

Excursions.yml

oneToOne:
  places:
    targetEntity: Places
    mappedBy: excursions

Excursion has one place_id. so $exccursion->getPlaces() returns ONE row only.

Now, when i trying to insert a value to the Places table, Doctrine2 says Not null violation: 7 ERROR: null value in column "idx" violates not-null constraint

I have no idea why this is happening. If i remove manyToOne then insert works. But this time getPlaces() is not working.

UPDATE

The probloem is, i use mappedBy against the database. I should only do this:

Places.yml

manyToOne:
  --remove--

Excursions.yml

oneToOne:
  places:
    targetEntity: Places
    joinColumn:
        name: place_id
        referencedColumnName: idx

This solves the problem. But i found this by trying/playing randomly. So, i don't know why :) Anyone knows that please explain me.

Upvotes: 1

Views: 317

Answers (1)

Mats Rietdijk
Mats Rietdijk

Reputation: 2576

First of all the mapping is incorrect. You should not have ManyToOne in Places.yml and the inversed side mapped as OneToOne in Excursions.yml. This is most likely why you run in to those errors.
Also you want an Excursion to have one Places object linked to it but Places could have more Excursions objects if i understand your question right. So you mapping should look like this:

# Places.yml
OneToMany:
    excursions:
        tagertEntity: Excursions
        mappedBy: places

And

# Excursions.yml
ManyToOne:
    places:
        targetEntity: Places
        inversedBy: excursions
        joinColumn:
            name: places_id
            referencedColumnName: id

Note that:

  1. The ManyToOne relationship should be inside the entity having only 1 of the other
  2. The OneToMany relationship should be inside the entity having multiple objects of the other
  3. joinColumn: name: should have the name of the column that you want created in the database
  4. joinColumn: referencedColumnName: should have the field from the target entity that you want to use to map the relationship with (I recommend you to use id as it is unique)

After you created this mapping run the following command:

php app/console doctrine:generate:entities BUNDLE_PREFIX

Were BUNDLE_PREFIX would be the first part of you bundles name. This will generate all the correct getters and setters. Don't forget to update you database schema too:

php app/console doctrine:schema:update --force

As some last advise I recommend (except if you intended it to be this way) you to change your entity names to Excursion and Place as each object should hold only 1 place or excursion.

Upvotes: 3

Related Questions