2013-08-21 76 views
0

我按照這裏的文檔http://symfony.com/doc/current/book/doctrine.html 我有一個問題。如何將數據庫記錄與對象關聯

我創建了類別和產品模型之間的關係。該數據庫是否已正確更新,模型類有正確的getter和setter方法,但如果我嘗試下面的代碼運行:

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

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

我得到一個錯誤:

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

我檢查出來和類別模型類有getName()方法,它是一個公共方法。

Product.orm.yml看起來像

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(); 
    } 
... 

什麼問題?

回答

1

您正在檢索示例代碼中的$category而不是$product

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

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

注意,你忘了getManager()

編輯:您需要使用findOneById()而不是findById。第一種方法將只返回一個單一結果(您的對象),findBy*將返回一個結果數組,您不能在循環內不通過它的情況下調用getCategory()

+0

我嘗試了不同的選擇,但它不起作用。 'FatalErrorException:錯誤:調用成員函數getCategory()' – deem

+0

爲什麼你有那些'* .orm.yml'文件?你確定產品1有一個類別? –

+0

我使用了控制檯命令,並且它已經生成。 BTW文檔沒有說'getManager()'(http://symfony.com/doc/current/book/doctrine.html) – deem

相關問題