问题描述
我在。
我暂时试图通过卡片一个定义的参数的值到findOneByIndex。
I am stuck at the moment trying to pass the value of a defined parameter into findOneByIndex.
所以如果我执行以下 $ script = $ repository-> findOneByIndex(1);
它工作完美。
但是如果我执行以下 $ script = $ repository-> findOneByIndex($ user);
,则无法使用用户的值进行搜索。
So if I do the following $script = $repository->findOneByIndex(1);
it works perfectly.But if I do the following $script = $repository->findOneByIndex($user);
it fails to search with the value of user.
在routing.yml中,我有这个模式:platform / designs / users / {user} / showuser
并在控制器我只是在showuserAction下这样做:
In routing.yml, I have this pattern: platform/designing/users/{user}/showuser
and in the controller I simply do this under the showuserAction:
$repository = $this->get('doctrine_mongodb')->getManager()->getRepository('MyMpBundle:Scripts');
$script = $repository->findOneByIndex($user);
任何帮助将不胜感激:)。
Any help would be appreciated :).
推荐答案
在你的最后一个代码示例中, $ user
变量的类型是什么?我认为它可能是一个字符串,如果它是一个路由参数,并从URI。您可以使用 var_dump()
一次获取类型和值。
In your last code example, what is the type of the $user
variable? I assume it may be a string if it's a routing parameter and coming from the URI. You can use var_dump()
to get the type and value in one shot.
根据之前的评论,你说脚本文件有以下字段:
Based on an earlier comment, you said that the Scripts document had the following fields:
- _id
- name(string)
- description(string)
- index(integer)
- user_id(integer)
- _id
- name (string)
- description (string)
- index (integer)
- user_id (integer)
如果您的MongoDB文档中的索引
字段是整数,则需要使用整数查询。例如, findOneByIndex('1')
在其字段中与整数 1
不匹配。这里最好的做法是您的值到查询前的适当类型。也许最好停止依赖于魔术DocumentRepository方法,并明确定义您自己的 findBy
方法,内部进行转换。然后,您的控制器可以直接从路由或请求参数传递数字字符串,而不必担心自己执行整数转换。
If the index
field in your MongoDB document is an integer, you will need to use an integer in the query. For instance, the findOneByIndex('1')
will not match a document with integer 1
in its field. A best practice here is to cast your values to the appropriate type before querying. It may also be best to stop relying on the magic DocumentRepository methods and explicitly define your own findBy
methods, which do the casting internally. Then, your controller can pass a numeric string directly from a routing or request parameter and not have to worry about doing the integer cast on its own.
另外,要评论您的原始代码示例:
Also, to comment on your original code example:
$script = $repository->findOneByIndex($user);
这是针对路由模式 platform / designs / users / {user} / showuser
。你说没有找到结果。我假定您的控制器的 $ user
参数是用户ID。如果是这样,为什么要查询索引
字段而不是 user_id
?
This was for the routing pattern platform/designing/users/{user}/showuser
. You said that this failed to find a result. I assume the $user
argument to your controller is a user ID. If that is the case, why were you querying on the index
field instead of user_id
?
这篇关于无法将参数的值传递给findOneBy Symfony存储库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!