Symfony,Doctrine更新无法按预期工作

时间:2016-01-26 11:24:46

标签: php symfony doctrine

嘿所有我有这个有线错误,我无法克服。我使用Symfony Framweork和Doctrine进行数据库交互。我正在尝试开发一个简单的CRUD API来掌握一些概念。

实际问题是,当我尝试更新数据库中的项目时,只有当项目的ID位于数据库内部时才会起作用,否则我会收到此错误:

Error: Call to a member function setTitle() on a non-object 

查看我的存储库:

<?php

namespace BooksApi\BookBundle\Repositories;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Query\QueryException;

class UpdateBookRepository
{
    /**
     * @var EntityManager
     */
    public $em;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(
        EntityManager $entityManager
    ){
        $this->em = $entityManager;
    }

    public function updateBook($id, $update)
    {
        try {
            $book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')
                ->find($id);

            $book->setTitle($update);
            $this->em->flush();
        } catch (\Exception $em) {
            throw new QueryException('003', 502);
        }

        return $book;
    }
} 

我的工厂:

<?php

namespace BooksApi\BookBundle\Repositories;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Query\QueryException;

class UpdateBookRepository
{
    /**
     * @var EntityManager
     */
    public $em;

    /**
     * @param EntityManager $entityManager
     */
    public function __construct(
        EntityManager $entityManager
    ){
        $this->em = $entityManager;
    }

    public function updateBook($id, $update)
    {

        $book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')
            ->find($id);

        if ($book)
        {
            try {
                $book->setTitle($update);
                $this->em->flush();
            } catch (\Exception $em) {
                throw new QueryException('003', 502);
            }

            return $book;
        } else {
            return false;
        }
    }
} 

工厂处理响应的真或假,所以如果我将尝试更新ID不在DB中的项目,工厂应该用false, 'Unable to Update Book'回复而不是我得到上述错误,任何想法为什么伙计们..?

2 个答案:

答案 0 :(得分:1)

@Tomazi,您可以通过在调用&#34; setTitle&#34;之前检查您的对象是否存在来避免错误。方法。

public function updateBook($id, $update)
{
    $book = $this->em->getRepository('BooksApiBookBundle:BooksEntity')->find($id);

    if ($book) {
        $book->setTitle($update);
        $this->em->flush();

        return $book;
    }

    return null;
}

答案 1 :(得分:0)

在继续执行代码之前,请确保$ book对象不为空。该错误表明$ book为空/空。 此外,坚持您的对象,然后再使用 flush

$this->em->persist($book);
$this->em->flush();
相关问题