3

次のような非常に基本的なスキーマがあります。

コメント.yml:

manyToOne:
  pages:
    targetEntity: Pages
    inversedBy: comments
    joinColumn:
      name: page_id
      referencedColumnName: idx

... other things ...

Pages.yml:

oneToMany:
  comments:
    targetEntity: Comments
    mappedBy: pages
    cascade: ["persist"] // i added this later but has no effect for both persist and merge.
    orderBy:
      idx: desc

... other things ...

今、すべてがうまく機能しています。から取得PagesCommentsにすることができます。問題は、データベースに新しい行を挿入しようとすると、.page_idnull

例:

$comment = new Comments();
$comment->setPageId(2); // it is "2"
$comment->setText($textData);

$this->_em->persist($comment);
$this->_em->flush($comment);

結果は false です。例外をスローし、SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "page_id" violates not-null constraint.

oneToManyと ManyToOne の関係を削除すれば、うまくいきます! それらを使用すると、与えてもnullと表示されます...

私の間違いはどこですか?どんな助けやアイデアも大歓迎です!

編集

私はこの方法を見つけました:getReference()

$item = $em->getReference('MyProject\Model\Item', $itemId);
$cart->setPage($item);

現在は機能しいますが、これが正しい方法かどうかはわかりません。私に光を当ててください。

基本的に、ページテーブルを変更せずに(削除も更新もせずに)コメントを追加したいです。しかし、ManyToOne と OneToMany としてまとめてフェッチしたいのです。

4

1 に答える 1

3

When You want to add a page to the Comments entity You should call a method like $comment->setPage($page) this method is automatically generated if you use the php app/console doctrine:generate:entities command line. The $page object should be the $page object loaded from the database. e.g.

$page = $this->getDoctrine()->getRepository('Pages')->findOneBy(array('id' => $pageId));

$comment = new Comments();
$comment->setPage($page);
$comment->setText($textData);

$this->_em->persist($comment);
$this->_em->flush();

If this doesn't help You, please post your code from your controller and the pages and comments entity.

于 2012-10-18T21:27:25.780 に答える