Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 - Insert new item in database

Tags:

doctrine-orm

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

like image 770
Raul Avatar asked Feb 24 '23 23:02

Raul


2 Answers

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();
like image 155
blacktie24 Avatar answered Mar 12 '23 07:03

blacktie24


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.

like image 39
beberlei Avatar answered Mar 12 '23 07:03

beberlei