Reputation: 310
I try get from database id value from User Entity.
$id = $this->getDoctrine()->getRepository('MyappUserBundle:User')->findByUsername($username);
and i get this:
Array
(
[0] => MyApp\UserBundle\Entity\User Object
(
[id:protected] => 1
[age:protected] => 22
[city:protected] =>
[state:protected] =>
[sex:protected] =>
[avatar:protected] => 99small-man-dancing-with-cat.jpg
[username:protected] => yeps
etc...
I have question:
How can I get id value from this object?
Upvotes: 1
Views: 1606
Reputation: 666
The "findByUsername" method returns a User object, so in order to get the user id (assuming you already have a "getId" public function in your User entity) you would have to do something like this:
$user = $this->getDoctrine()->getRepository('MyappUserBundle:User')->findByUsername($username);
$userId = $user->getId();
Upvotes: 0
Reputation: 17759
findByX
returns an array where as findOneByX
will return a single object.
As you are searching for a specific username it would make more send to use findOneByX
and then you can get the id
from the return User
like..
$user = $this->getDoctrine()
->getRepository('MyappUserBundle:User')
->findOneByUsername($username)
;
$id = $user->getId();
It would also make sense to add a null check incase no user was found like..
if (null === $user) {
throw new \Exception(sprintf('User with username "%s" not found', $username));
}
$id = $user->getId();
Upvotes: 1