关联字段的实体类型的预期值得到“字符串”

时间:2016-12-30 16:48:22

标签: php symfony

我正在尝试插入我的评论表中,在我的控制器中我有:

public function indexAction(Request $request, $id)
{
    if($id != null)
    {
        // Create a new Review entity
        $review = new Review();

        $form = $this->createForm(ReviewType::class, $review,[
            'action' => $request->getUri()
        ]);

        $form->handleRequest($request);

        if($form->isValid()) {

            $manager = $this->getDoctrine()->getManager();
            $review->setPosted(new \DateTime());
            $review->setBookID($id);
            $review->setUserID($this->getUser());
            $manager->persist($review);
            $manager->flush();

        }

        return $this->render('ReviewBookBundle:Book:index.html.twig',
            ['form' => $form->createView());
    }
}

然而,在$review->setBookID($id);行上我收到此错误:

Expected value of type "Review\BookBundle\Entity\Book" for association field "Review\ReviewsBundle\Entity\Review#$bookID", got "string" instead.

我如何克服这个问题?因为我尝试创建Book实体并设置bookID,然后将Book实体传递到$ review-setBookID,如下所示:

$review->setBookID($book);

但是仍然不起作用?

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

在审核实体中添加此内容:

/**
 * @var Book
 * @ORM\ManyToOne(targetEntity="YourBundle\Entity\Book", inversedBy="review", fetch="LAZY")
 * @ORM\JoinColumn(name="book_id", referencedColumnName="id")
 */
protected $book;

/**
 * @return Book
 */
public function getBook()
{
    return $this->book;
}

/**
 * @param $book
 */
public function setBook($book)
{
    $this->book = $book;
}

并使用:

$review->setBook($book);

$book必须是Book实体的实例

修改

图书实体:

public function __construct() {
    $this->reviews = new ArrayCollection();
}

/**
 * @var Review
 * @ORM\OneToMany(targetEntity="YourBundle\Entity\Review", fetch="LAZY")
 * @ORM\JoinColumn(name="review_id", mappedBy="book", referencedColumnName="id")
 */
protected $reviews;

/**
 * @return Review
 */
public function getReviews()
{
    return $this->reviews;
}

/**
 * @param Review $review
 */
public function addReview(Review $review)
{
    $this->reviews->add($review);
}

/**
 * @param Review $review
 */
public function removeReview(Review $review)
{
    $this->reviews->removeElement($review);
}