gpt4 book ai didi

php - 教义 : Multiple orWhere with LIKE condition

转载 作者:行者123 更新时间:2023-12-02 21:22:50 26 4
gpt4 key购买 nike

使用具有结构的表:

id              | count
/string/id1 | 3
/string/id1/r1 | 2
/string/id1/r2 | 1
/string/id2/r1 | 2
/string/id2 | 3
/string/id2/r1 | 2
/string/id3/r1 | 5

我想选择id中需要子字符串的所有行。
即我需要 id 中包含子字符串的所有行: /string/id1/string/id2

查询应该很简单 - 简单的 sql:

select * from table_name where id LIKE '/string/id1%' OR id LIKE '/string/id2%';

结果应该是:

id              | count
/string/id1 | 3
/string/id1/r1 | 2
/string/id1/r2 | 1
/string/id2/r1 | 2
/string/id2 | 3
/string/id2/r1 | 2

不幸的是,如果您尝试在 symfony 和doctrine2 中使用相同的查询:

$ids = array('/string/id1', '/string/id2');

$query = $this->createQueryBuilder('r')
->select('r');
foreach ($ids as $id) {
$query->orWhere("r.linkedId LIKE :id ")
->setParameter('id', $id."%");
}
$plainQuery = $query->getQuery()->getSQL();
$results = $query->getQuery()->getResult();

普通查询看起来与 select * from table_name where id LIKE '/string/id1%' OR id LIKE '/string/id2%'; 相同,但结果却不然。

结果仅包含 ids 中最后一项的行 - /string/id2

id              | count
/string/id2/r1 | 2
/string/id2 | 3
/string/id2/r1 | 2

如何解决?我的错误在哪里?您有什么建议吗?

最佳答案

我不能确定,但​​在我看来,这与参数标识符发生冲突。

这就是您想要做的:

  • 构建基本的 SELECT * FROM table_name 语句
  • 附加 WHERE r.linkedId LIKE :id
  • id参数的值设置为/string/id1%
  • 追加 OR r.linkedId LIKE :id
  • id 参数的值设置为 /string/id2%(覆盖之前的值)<-- 错误

基本上,您是在告诉 Doctrine 用新值覆盖先前定义的 id 参数值。

您可以轻松解决这个问题。只需将 $i 添加到参数名称

foreach ($ids as $i => $id) { 
// $i here has the value of 0,1,2, etc...

$query->orWhere("r.linkedId LIKE :id$i" ) // append $i
->setParameter("id$i", $id."%"); // but also append it here
}

请务必使用双引号,或连接 ("id". $i) ;)

关于php - 教义 : Multiple orWhere with LIKE condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26319576/

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