如何返回空的 Doctrine_Collection?
我有一个返回 Doctrine_Collection 的方法,带有 whereIn()
子句:
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
}
但是,当 $values
是空数组时,此方法返回所有行位于 AnomalyTable 中。这不是意外行为,如 Doctrine 文档中所述,并写在这里: Doctrine where in with Doctrine_Query
但是,当 $values
是空数组时,我想返回一个空的 Doctrine_Collection
而不是查询结果。
关于我该如何做到这一点有什么想法吗?
谢谢=)
编辑:
添加一个不可能的子句,例如 ->where('1=0')
就可以解决问题,但这是对数据库服务器的不必要的请求。有人有更好的主意吗?
I've a method that returns a Doctrine_Collection, with a whereIn()
clause :
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
}
However, when $values
is an empty array, this method return all the rows that are in the AnomalyTable. This isn't an unexpected behavior, as documented in Doctrine documentation, and written here : Doctrine where in with Doctrine_Query
However, I would like to return an empty Doctrine_Collection
instead of the result of my query, when $values
is an empty array.
Any ideas on how I can do that ?
Thanks =)
Edit:
Adding an impossible clause, like ->where('1=0')
would do the trick, but it is an unnecessary request to the DB server. Does anyone have a better idea ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
那么(您还需要执行方法来获取查询结果!每次返回类型都是相同的):
And what about (you need also the execute method to get the result of the query ! with that the return type will be the same everytime) :
就价值而言,我假设您的意思是
$values
对吗?只需添加一些内容来检查值是否为空,然后手动提供一个空集合。By value, I assume you mean
$values
right? just add something to check if values is empty and then manually supply an empty collection.我认为这是不可能的。
Doctrine_Collection 不仅仅是对象的结果集/数组。它还具有删除和添加对象并保持该状态的方法。
这可能也是许多本机 Doctrine 函数在未找到结果时返回 FALSE 的原因。 (例如,NestedSet 函数)。
因此,对于您来说,最好也返回 FALSE。或者可能是一个空数组。作为 Doctrine_Collection 的两个数组都可以在
foreach
循环和count
函数中使用。如果您想使用
delete
和add
函数,您只需调用构造函数即可。I think it's impossible to do that.
The Doctrine_Collection is more than a resultset/array of objects. It also has means of deleting and adding objects and keeping that state.
That's probably also why many native Doctrine functions return
FALSE
when no results were found. (For instance, the NestedSet functions).So, for you it's probably best to return FALSE as well. or maybe an empty array. Both arrays as Doctrine_Collection can be used in a
foreach
loop andcount
function.Should you want to use the
delete
andadd
functions, you could just call the constructor.我个人使用以下技巧:
即使有点黑客,效果也很好。
I personnaly use the following trick:
Works great even if somewhat hackish.