我正在尝试使用原始查询显示表“Post”的某些字段:
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT * FROM Post WHERE category_id = 1");
$statement->execute();
$posts = $statement->fetchAll();
...
foreach($posts as $post) {
$xml .= $post->getId();
$xml .= $post->getTitle();
$xml .= $post->getContent();
}
我遇到错误“FatalErrorException:错误:在...中的非对象上调用成员函数 getId()” 所有这些 setter/getter 都在我的 Post 实体中。关于我做错了什么有什么建议吗?
[编辑]
$em = $this->getDoctrine()->getManager();
$post_repository = $em->getRepository('MyBundle:Post');
$posts = $post_repository->findBy(array('category_id' => 1));
foreach($posts as $post) {
$xml .= $post->getTitle();
}
返回我“无法识别的字段:category_id”。
我的帖子类(class):
class Post
{
/**
* @ORM\ManyToOne(targetEntity="MyBundle\Entity\Category", inversedBy="post")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
* })
*/
private $category;
/**
* Set category
*
@param MyBundle\Entity\Category $category
*/
public function setCategory(\MyBundle\Entity\Category $category)
{
$this->category = $category;
}
/**
* Get category
*
@return MyBundle\Entity\Category
*/
public function getCategory()
{
return $this->category;
}
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
....
最佳答案
为什么在这里直接使用您的连接?您应该考虑为您的“posts”类使用实体存储库。例如:
$posts = $em->getRepository('YourBundle:Post')->findBy(array('category_id' => 1));
这应该可行,只需将 YourBundle:Post
替换为正确的包和类名称即可。对于 category_id
也是如此,如果没有您的实现,我无法猜测它是类属性还是映射名称。
我建议您阅读更多关于the official Doctrine documentation的内容提高您对该主题的了解。
关于Symfony 主义 : get field value in foreach loop on fetchAll(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19766304/