我按照這裏的文檔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();
}
...
什麼問題?
我嘗試了不同的選擇,但它不起作用。 'FatalErrorException:錯誤:調用成員函數getCategory()' – deem
爲什麼你有那些'* .orm.yml'文件?你確定產品1有一個類別? –
我使用了控制檯命令,並且它已經生成。 BTW文檔沒有說'getManager()'(http://symfony.com/doc/current/book/doctrine.html) – deem