I want to make this query in SQLite using DQL
//// src/Repository/PostRepository.php
public function hasPreviousPost($id,$slug): array
{
$em = $this->getEntityManager();
$query = $em->createQuery('SELECT p FROM App\Entity\Post p WHERE p.id < '.$id.' AND p.slug = '.$slug);
$posts = $query->getResult();
return $posts;
}
And I call this function from the PostController like that
//// src/Controller/PostController.php
$posts = $this->getDoctrine()->getRepository(Post::class)->findAll();
foreach ($posts as $post){
$hasPreviousPost = $this->getDoctrine()->getRepository(Post::class)->hasPreviousPost($post->id(),$post->Slug());
}
But when I run the code, I get this error " [Semantical Error] line 0, col 48 near 'pizza-mia': Error: 'pizza' is not defined. "
pizza-mia is what $slug contains, a string.
This is my Post entity.
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
$countPosts = 0;
/**
* @ORM\Entity(repositoryClass="App\Repository\PostRepository")
* @ORM\Table(name="post")
*/
class Post
{
/**
* @ORM\Column(type="integer")
* @ORM\Column(unique=true)
*/
private $id;
/**
* @ORM\Id
* @ORM\Column(type="text")
* @ORM\Column(unique=true)
*/
private $postId;
/**
* @ORM\Column(type="text")
*/
private $slug;
/**
* @ORM\Column(type="text")
*/
private $message;
/**
* @ORM\Column(type="boolean",nullable=true)
*/
private $isScheduled;
/**
* @ORM\Column(type="integer")
*/
private $scheduledPublishTime;
function __construct($postId,$slug,$message)
{
global $countPosts;
$countPosts++;
$this->postId=$postId;
$this->id=$countPosts;
$this->slug=$slug;
$this->message=$message;
$this->isScheduled=false;
$this->scheduledPublishTime=0;
}
public function PostId(): ?string
{
return $this->postId;
}
public function id(): ?int
{
return $this->id;
}
public function Slug(): ?string
{
return $this->slug;
}
public function Message(): ?string
{
return $this->message;
}
public function IsScheduled(): ?bool
{
return $this->isScheduled;
}
public function changeIsScheduled(?bool $isScheduled): self
{
$this->isScheduled = $isScheduled;
return $this;
}
public function ScheduledPublishTime(): ?int
{
return $this->scheduledPublishTime;
}
public function changeScheduledPublishTime(int $scheduledPublishTime): self
{
$this->scheduledPublishTime = $scheduledPublishTime;
return $this;
}
}
Any help will be appreciated.
Try it this way.
$query = $em->createQuery('SELECT p FROM App\Entity\Post p WHERE p.id < :id AND p.slug = :slug');
$query->setParameter('id', $id);
$query->setParameter('slug', $slug);
:id
and :slug
stand for a named parameter
My strong assumption is that you simply are missing the ' ' to have your $slug defined as string in your query. But using parameters like above makes it more readable as well.
Find an explanation about named or numbered parameters in the documentation