I am using Symfony (version 2.5.0-DEV) and the doctrine mongodb cookbook on http://symfony.com/doc/current/bundles/DoctrineMongoDBBundle/index.html.
I am stuck at the moment trying to pass the value of a defined parameter into findOneByIndex.
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.
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 :).
Using the echo function, I can see that it works when value is simply entered (not parameter). Please see full controller script below. Any help would be appreciated :)
Thanks jmikola. the {user} is more or less a parameter and it carries a value. I query on the index to test as well as the user_id too but none of them works (using index to test as it has same integer as user_id and to avoid underscore in user_id). The issue is that passing the $user to the controller and using the
findOneBy
only works with Id not with index or user_id. That is:My document script is pasted below:
This value should be an integer, not object. Please pass the id, or index value - I don't know how it's stored in mongodb.
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 usevar_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:
If the
index
field in your MongoDB document is an integer, you will need to use an integer in the query. For instance, thefindOneByIndex('1')
will not match a document with integer1
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 ownfindBy
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:
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 theindex
field instead ofuser_id
?Do you pass
$user
toshowuser
action? like this (notice $user as parameter):PS. I'd recommend you to change var
$user
to$userId
just not to mistake it with $user object