I'm trying to display some fields of a table 'Post' using a raw query :
$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();
}
I've got an error "FatalErrorException: Error: Call to a member function getId() on a non-object in ..." All those getters are right in my Post entity. Any suggestion about what I'm doing wrong ?
[EDIT]
$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();
}
Returns me "Unrecognized field: category_id".
My Post 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;
....
Why using directly your connection here? You should consider using the entity repository for your "posts" class. For example :
$posts = $em->getRepository('YourBundle:Post')->findBy(array('category_id' => 1));
this should work, just replace the YourBundle:Post with the proper bundle and class names. Same for the category_id, I can't guess without your implementation if it's the class property or the mapping name.
I suggest you to read more on the official Doctrine documentation to improve your knowledge on the subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With