0

I follow the docs from here http://symfony.com/doc/current/book/doctrine.html and I have a issue.

I created a relation between the category and the product model. The database has been updated correctly, model classes have right getters and setters, but if I try to run following code:

$product = $this->getDoctrine()->getRepository('AcmeStoreBundle:Product')
            ->findById(1);

$categoryName = $product->getCategory()->getName();

I gets an error:

FatalErrorException: Error: Call to a member function getName() on a non-object in D:\www\Symfony\src\Acme\StoreBundle\Controller\DefaultController.php line 28

I checked it out and the category model class has getName() method and it is a public method.

My Product.orm.yml looks like

Acme\StoreBundle\Entity\Product:
    type: entity
    manyToOne:
        category:
            targetEntity: Category
            inversedBy: products
            joinColumn:
                name: category_id
                referencedColumnName: id
    table: null
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
        name:
            type: string
            length: 255
        price:
            type: decimal
    lifecycleCallbacks: {  }

Category.orm.yml

Acme\StoreBundle\Entity\Category:
    type: entity
    oneToMany:
        products:
            targetEntity: Product
            mappedBy: category
    table: null
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
        name:
            type: string
            length: '255'
    lifecycleCallbacks: {  }

Product.php

...
    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    protected $category;
...

Category.php

...
    /**
     * @ORM\OneToMany(targetEntity="Product", mappedBy="category")
     */
    protected $products;

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

What's the problem?

4

1 回答 1

1

You are retrieving a $category instead of a $product in your sample code.

$product = $this->getDoctrine()->getManager()->getRepository('AcmeStoreBundle:Product')->findOneById(1);

$categoryName = $product->getCategory()->getName();

note that you forgot the getManager()

Edit : You need to use findOneById() instead of findById. The first method will return only one single result (your object), the findBy* will return you an array of results on which you can't call getCategory() without traversing it inside a loop.

于 2013-08-21T12:48:06.700 回答