gpt4 book ai didi

php - Symfony findOneBy : column type array returns null

转载 作者:行者123 更新时间:2023-11-29 10:44:07 30 4
gpt4 key购买 nike

我有一个带有列类型数组的实体

/**
* Report entity
*
* @ORM\Table(name="report")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ReportRepository")
*/
class Report
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @var array
*
* @ORM\Column(name="selectedCountries", type="array", nullable=true)
*/
private $selectedCountries;

在数据库中,我有一条记录,存储为:

+-------------------------+
| selectedCountries |
+-------------------------+
| a:0:{} |
+-------------------------+

当我这样做时:

$report = $this->reportRepository->findOneBy(array('selectedCountries' => []));

我得到 null,但我不知道为什么。

数据库连接、实体、存储库等工作正常:当我将此数组包含在 findOneBy() 中时,它找不到结果。

最佳答案

Symfony profiler的帮助下,我调试了 Doctrine 所做的查询,发现我需要使用 simple_array 而不是 array 作为 @ORM\Column 类型

当我使用数组作为列类型时:只要将数据保存到数据库(如 a:0:{}), Doctrine 就会序列化该数组。这种方法的问题是当我尝试运行 findby 时:

  • 如果我使用数组作为参数,则 Doctrine 查询如下所示:..AND t0.selectedCountries IN ('de')..
  • 如果我使用序列化数组, Doctrine 会像这样转义:..AND
    t0.selectedCountries = 's:19:\"a:1:{i:0;s:2:\"de\";}\";' ..

所以在这两种情况下都找不到记录!

但是通过使用 simple_array Doctrine 查询看起来像: .. AND t0.selectedCountries IN ('de') .. 这是完美的,因为表中的数据是现在另存为:

+-------------------------+
| selectedCountries |
+-------------------------+
| de |
+-------------------------+

此方法的唯一问题是当您在数组中有更多元素时:selectedCountries => de,fr,uk 并且希望通过此进行搜索。为此,您应该做额外的工作:

@ORM\HasLifecycleCallbacks() 添加到您的实体并在插入之前对数组进行排序

/**
* @ORM\PrePersist
*/
public function setSelectedCountriesValue()
{
sort($this->selectedCountries);
}

在您实体的存储库中使用 Query Builder并在尝试查找结果时对数组进行排序。

 $qb = $this->getEntityManager()->createQueryBuilder();

$qb->select('r')
->from('AppBundle:Report', 'r')
...

if ($creteria['selectedCountries']) {
sort($creteria['selectedCountries']);
$qb->andWhere('r.selectedCountries= :selectedCountries')
->setParameter('selectedCountries', implode(',', $creteria['selectedCountries']));
}

关于php - Symfony findOneBy : column type array returns null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44944254/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com