I don't have a lot of experience with symfony or doctrine but I'm in a weird situation.
I got a simple User and Post entity. The thing is that Users can post things when they are logged.
The problem is that I wanted to link my table "post" and "user" with post.user_id and user.id
So with doctrine I decided to make a simple manyToOne relation in Post :
(Post.orm.yml)
Whatever\PostBundle\Entity\Post:
type: entity
table: post
repositoryClass: Whatever\PostBundle\Repository\PostRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
content:
type: text
userId:
type: integer
column: user_id
createdAt:
type: datetime
column: created_at
manyToOne:
user:
targetEntity: Whatever\UserBundle\Entity\User
lifecycleCallbacks: { }
Entities generated and doctrine:schema:update done
Now I can get User informations with the posts as I wanted BUT ALSO can't post anything anymore because of user_id null
An exception occurred while executing 'INSERT INTO post (content, user_id, created_at) VALUES (?, ?, ?)' with params ["content of the post", null, "2017-04-21 11:27:04"]:
As you can see the user_id is null (I tried to set it manually in the controller, in the entity construct or with a form field, same result)
It's not over. Because if I comment/remove the part of Post.orm.yml :
manyToOne:
user:
targetEntity: Whatever\UserBundle\Entity\User
Then I can post again ... But I don't understand why. (and btw I can't get users informations with the posts anymore. So I still need it)
Can someone give me an explanation ? I've been on this problem for 2 days. You're my last hope.
In your fields definitions, remove userId
. Symfony will take care of that by your ManyToOne definition. See the docs for reference.
Whatever\PostBundle\Entity\Post:
type: entity
table: post
repositoryClass: Whatever\PostBundle\Repository\PostRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
content:
type: text
// Remove the next few lines
// userId:
// type: integer
// column: user_id
createdAt:
type: datetime
column: created_at
manyToOne:
user:
targetEntity: Whatever\UserBundle\Entity\User
lifecycleCallbacks: { }