Doctrine 2 - Insert a new item into the database

I am trying to make something very simple .. but I am mistaken and I do not know what the problem is. I'm just trying to insert a new item into the database using Doctrine 2:

$favouriteBook = new UserFavouriteBook; $favouriteBook->user_id = 5; $favouriteBook->book_id = 8; $favouriteBook->created_at = new DateTime("now"); $this->_em->persist($favouriteBook); $this->_em->flush(); 

As you can see .. very simple, but give me the following error:

 Error: Message: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null 

Obviosly, if I create a "dump" before "persist" and "flush" from $ favoriteBook, everything looks right.

This is my favoriteBook object:

 /** @Column(type="integer") * @Id */ private $user_id; /** @Column(type="integer") * @Id */ private $book_id; /** * @ManyToOne(targetEntity="Book", inversedBy="usersFavourite") * @JoinColumn(name="book_id", referencedColumnName="id") */ private $book; /** * @ManyToOne(targetEntity="User", inversedBy="favouriteBooks") * @JoinColumn(name="user_id", referencedColumnName="id") */ private $user; /** @Column(type="datetime") */ private $created_at; public function __get($property) { return $this->$property; } public function __set($property, $value) { $this->$property = $value; } 

Can anyone understand what the problem is? .. I don’t know what else to try .. Thanks

+4
source share
2 answers

I think that, according to Beberlei, inside your favoriteBook object, you do not need to define user_id and book_id as class properties, b / c your book and user settings already recognize them as the corresponding connection columns.In addition, your attempt to save the favoriteBook object does not failed because you need to establish book and user associations in your favoriteBook object, not foreign keys. So it would be:

 $favouriteBook = new UserFavouriteBook; $favouriteBook->book = $book; $favouriteBook->user = $user; $favouriteBook->created_at = new DateTime("now"); $this->_em->persist($favouriteBook); $this->_em->flush(); 
+6
source

You map foreign keys and associations. You must change the association, not the foreign key field. Its a bad practice to display them both, you must completely remove $ book_id and $ user_id.

+2
source

Source: https://habr.com/ru/post/1341612/


All Articles