我想使用DQL在SQLite中进行此查询
//// 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;
}
我像这样从PostController调用此函数
//// 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());
}
但是当我运行代码时,出现此错误 “ [语义错误]第0行,'pizza-mia'附近的col 48:错误:'pizza'未定义。”
$ slug包含的比萨饼是一个字符串。
这是我的Post实体。
<?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;
}
}
任何帮助将不胜感激。
答案 0 :(得分:0)
以这种方式尝试。
$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
和:slug
代表命名参数
我的强烈假设是,您只是缺少''来将$ slug定义为查询中的字符串。 但是,使用上述类似的参数也会使其更具可读性。
中找到有关命名或编号参数的说明