I have two classes:
News:
/** @Entity @Table(name="news") */
class News {
/**
* @Id @GeneratedValue @Column(type="integer")
* @var integer
*/
protected $id;
/**
* @Column(type="string", length=100)
* @var string
*/
protected $title;
/**
* @Column(type="text")
* @var string
*/
protected $content;
/**
* @ManyToOne(targetEntity="User", inversedBy="news")
* @JoinColumn(referencedColumnName="id")
*/
protected $author;
/**
* @ManyToOne(targetEntity="NewsCategory", inversedBy="news")
* @JoinColumn(referencedColumnName="id")
*/
protected $category;
/**
* @Column(type="datetime")
*/
protected $add_date;
# CATEGORY methods
public function setCategory($val) { if($val instanceof NewsCategory) $this->category = $val; }
public function getCategory() { return $this->category; }
}
NewsCategory:
/** @Entity @Table(name="news_category") */
class NewsCategory {
/**
* @Id @GeneratedValue @Column(type="integer")
* @var integer
*/
protected $id;
/**
* @Column(type="string", length=50, unique=TRUE)
* @var string
*/
protected $name;
/**
* @OneToMany(targetEntity="News", mappedBy="category")
*/
protected $news;
public function __construct() {
$this->news = new \Doctrine\Common\Collections\ArrayCollection;
}
public function setName($name) { $this->name = $name; }
public function getName() { return $this->name; }
public function getNews() { return $this->news; }
}
I want to download one news with this query:
$q = $this->db->createQuery("SELECT n FROM News n WHERE n.id = :id");
$q->setParameter('id', $_GET['id']);
$news = $q->getResult();
And next, I want to get id of a Category related to this news with
$news->getCategory()->getId()
With code above, I’m getting this error:
Fatal error: Call to undefined method DoctrineProxies\NewsCategoryProxy::getId() in C:\[...]\newsController.php on line 61
What’s wrong? Why my NewsCategory class can’t see getId() method?
It’s a good practice to allways declare your class’ members private and to generate getters and setters on your class members.
In your case, you don’t generate getters and setters (there is no
getId()method on yourNewCategoryclass).That’s how your
NewCategoryclass should look like :The generated proxies will not generate magically getters and setters on every of your properties (it would break the OOP’s encapsulation principle).
You can find more documentations about proxies here : http://www.doctrine-project.org/docs/orm/2.0/en/reference/configuration.html#proxy-objects