Raul
Raul

Reputation: 145

Doctrine 2 - Insert new item in database

I'm trying to make something very simple.. but I do wrong, and I don't know what is the problem. Just I'm trying to insert new item to database with 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.. is very simple, but that, give me next error:

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

Obviosly, if I make a "dump" before "persist" and "flush" of $favouriteBook, all looks be correct..

This is my "favouriteBook" entity:

/** @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;
}  

Anyone can image what is the problem? .. I don't know what else try.. Thanks

Upvotes: 4

Views: 21747

Answers (2)

blacktie24
blacktie24

Reputation: 5075

I think what beberlei is saying is that within your favouriteBook entity, you don't need to define the user_id and book_id as class properties, b/c the book and user properties you have set already recognize these as the relevant join columns. Also, your attempt to persist the favouriteBook entity failed because you need to set the book and user entity associations within the favouriteBook entity, not the 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();

Upvotes: 6

beberlei
beberlei

Reputation: 4337

You are mapping foreign keys and the associations. You have to modify the association not the foreign key field. Its bad-practice to map them both, you should remove $book_id and $user_id completly.

Upvotes: 2

Related Questions