我一直在努力学习Doctrine,我有一个博客帖子的实体,它引用了评论,它引发了以下错误: 注意:未定义的索引:post_id
无论post_id如何,它都会获得所有评论。这是我的映射:
/**
* @OneToMany(targetEntity="CommentsBundle\Entities\Comments", mappedBy="post_id")
*/
protected $comments;
修改
这是评论实体:
<?php
namespace CommentsBundle\Entities;
use Doctrine\ORM\Mapping AS ORM;
/**
* @Entity @Table(name="comments")
**/
class Comments
{
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @Column(type="string") */
protected $name;
/** @Column(type="string") */
protected $email;
/** @Column(type="string") */
protected $content;
/** @Column(type="string") */
protected $date;
/** @Column(type="integer") */
protected $user_id;
/** @Column(type="integer") */
protected $post_id;
/**
* @ORM\ManyToOne(targetEntity="ContentBundle\Entities\Posts", inversedBy="comments")
* @ORM\JoinColumn(name="post_id", referencedColumnName="id")
*/
protected $post;
public function setId( $id )
{
$this->id = $id;
return $this;
}
public function getId()
{
return $this->id;
}
public function setName( $name )
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setEmail( $email )
{
$this->email = $email;
return $this;
}
public function getEmail()
{
return $this->email;
}
public function setContent( $content )
{
$this->content = $content;
return $this;
}
public function getContent()
{
return $this->content;
}
public function setDate( $date )
{
$this->date = $date;
return $this;
}
public function getDate()
{
return $this->date;
}
public function setUser_id( $user_id )
{
$this->user_id = $user_id;
}
public function getUser_id()
{
return $this->user_id;
}
public function setPost_id( $post_id )
{
$this->post_id = $post_id;
return $this;
}
public function getPost_id()
{
return $this->post_id;
}
}
提前致谢!
答案 0 :(得分:1)
你必须在Entity的属性上编写mappedBy,而不是列。
基本上,实体的属性必须“相互交谈”。
$comments
由$post
映射,$post
由$comments
反转:
class Posts
{
/**
* @OneToMany(targetEntity="CommentsBundle\Entities\Comments", mappedBy="post")
*/
protected $comments;
}
class Comments
{
/**
* @ORM\ManyToOne(targetEntity="ContentBundle\Entities\Posts", inversedBy="comments")
* @ORM\JoinColumn(name="post_id", referencedColumnName="id")
*/
protected $post;
}
另外,我不会在您的$post_id
实体中定义Comments
。只需$post
,当您需要检索帖子的ID时:
public function getPost_id()
{
return $this->post->getId();
}
事情变得更加清洁。