Comment モデルを Post モデルにぶら下げる
CakePHP 風に表現すると Post hasMany Comment
といった感じです。
Comment モデルを作る
基本的に console が何でもやってくれます。
コマンド名を忘れても php app/console list
とすれば一覧が表示されます。
$ php app/console doctrine:generate:entity
# ブログバンドルにCommentモデルを追加します。
The Entity shortcut name: QuartetBlogBundle:Comment
# 今回はアソシエーションが目的なので、contentフィールドだけにします。
New field name (press <return> to stop adding fields): content
Field type [string]:
Field length [255]:
Generating the entity code: OK
Comment.php が生成されました。
アソシエーションの設定をする
Post モデルと Comment モデルの関連付けを行います。
<?php
// Post.php
/**
* @ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
private $comments;
Comment
の post
フィールドに自モデルが OneToMany
で関連付いているという意味です。
逆の参照も定義します。
// Comment.php
/**
* @ORM\ManyToOne(targetEntity="Post", inversedBy="comments");
*/
private $post;
Postのcommentsフィールドに自モデルがManyToOneで関連付いているという意味です。
メソッドの生成
アソシエーションの設定が完了したので、メソッドを生成します。 CakePHPと違ってファイルを置き換えず、不足分を書き足すので何も消える事はありません。
$ php app/console doctrine:generate:entities QuartetBlogBundle
Generating entities for bundle "QuartetBlogBundle"
> backing up Comment.php to Comment.php~
> generating Quartet\Bundle\BlogBundle\Entity\Comment
> backing up Post.php to Post.php~
> generating Quartet\Bundle\BlogBundle\Entity\Post
補足: 特定のモデルだけ更新したい場合
php app/console doctrine:generate:entities QuartetBlogBundle:{モデル名}
メソッド実行後
いろいろ生成されました。
<?php
// Post.php
/**
* Add comments
*
* @param \Quartet\Bundle\BlogBundle\Entity\Comment $comments
* @return Post
*/
public function addComment(\Quartet\Bundle\BlogBundle\Entity\Comment $comments)
{
$this->comments[] = $comments;
return $this;
}
/**
* Remove comments
*
* @param \Quartet\Bundle\BlogBundle\Entity\Comment $comments
*/
public function removeComment(\Quartet\Bundle\BlogBundle\Entity\Comment $comments)
{
$this->comments->removeElement($comments);
}
/**
* Get comments
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}
<?php
// Comment.php
/**
* Set post
*
* @param \Quartet\Bundle\BlogBundle\Entity\Post $post
* @return Comment
*/
public function setPost(\Quartet\Bundle\BlogBundle\Entity\Post $post = null)
{
$this->post = $post;
return $this;
}
/**
* Get post
*
* @return \Quartet\Bundle\BlogBundle\Entity\Post
*/
public function getPost()
{
return $this->post;
}
このままでは Post::$commentsの初期値がnullのままなのでコンストラクタに処理を追加します。
<?php
// Post.php
public function __construct()
{
$this->created = new \DateTime();
// ↓追記
$this->comments = new ArrayCollection();
}
テーブルスキーマ更新
忘れずに実行してください。
php app/console doctrine:schema:update --force
アソシエーションの定義はこんな感じです。 ManyToManyなど他のアソシエーションのドキュメントはDoctrineのORMのアソシエーションの章にあるので見てみましょう。