1

我有一个实体 Annonce 有标签 ManyToMany 到 Entity Tag

当我通过像这张图片这样的标签搜索 Annonce

在此处输入图像描述

我的问题是:例如,如果数据库中存在 Bike 标签,它将返回带有该标签的 Annonces,没有错误

如果我添加例如“汽车”之类的标签,数据库中不存在,则会出现错误:

仅允许具有标识符的实体将实体绑定到查询参数。

这是在我的控制器中

$annonces = $repository->findListByFilter($data->getTags());

这是存储库

public function findListByFilter($tags):array
{
    return $this->createQueryBuilder('c')
        ->innerJoin('c.tags', 'tags')
        ->where('tags IN (:value)')
        ->setParameter(':value', $tags)
        ->getQuery()->getResult();
}

有解决这个问题的方法吗?

----------附加信息--------------- 标记实体

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\TagRepository")
 */
class Tag
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $titre;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitre(): ?string
    {
        return $this->titre;
    }

    public function setTitre(string $titre): self
    {
        $this->titre = $titre;

        return $this;
    }

    public function __toString()
    {
        return $this->titre;
    }
}

公告实体

namespace App\Entity;

use App\Tag\Taggable;
class Annonce
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    public function __construct()
    {

        $this->tags = new ArrayCollection();

    }

    use Taggable;
}

类可标记

use App\Entity\Tag;

trait Taggable
{

    /**
     * @var array
     *php bin/console make:entity --regenerate App
     * @ORM\ManyToMany(targetEntity="App\Entity\Tag", cascade={"persist"})
     */
    private $tags;

    /**
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTags()
    {
        return $this->tags;
    }

    public function addTag(tag $tag)
    {
        if (!$this->tags->contains($tag)) {
            $this->tags[] = $tag;
        }
        return $this;
    }

    public function removeTag(tag $tag)
    {
        if ($this->tags->contains($tag)) {
            $this->tags->removeElement($tag);
        }

    }

    public function __construct()
    {
        $this->tags = new ArrayCollection();
    }
}
4

1 回答 1

1

您可以在此处执行以下两个选项之一:

  1. 将该新标签也存储在数据库中,然后继续findListByFilter()

  2. 不要存储新标签,而是修改:

在控制器中:

$annonces = $repository->findListByFilter($data->getTags());

在存储库中:

public function findListByFilter($tags):array
{
    $tagsText = [];
    foreach ($tags as $tag) {
      $tagsText[] = $tag->getTitre();
    }

    return $this->createQueryBuilder('c')
        ->innerJoin('c.tags', 'tags')
        ->where('tags.titre IN (:value)')
        ->setParameter(':value', $tagsText)
        ->getQuery()->getResult();
}

我在这里假设标签实体具有字段文本。

于 2019-03-13T08:41:34.490 回答