0

Can someone explain, why I get different results?

$user = new UserEn();
$user->setName("test");
$em->persist($user);

$result1 = $em->find('UserEn', 'test');

$result2 = $em->getRepository('UserEn')->findBy(array('name'=>'test'));

$q = $em->createQuery('select u from UserEn u where u.name = :name');
$q->setParameter('name', 'test');
$result3 = $q->getResult();

Only $result1 holds $user, which is what I expected, and the others are null. What's wrong? (Please don't say that I need to call $em->flush(); )

user1592714
  • 443
  • 4
  • 11

2 Answers2

1

Because Doctrine can't figure out that you are specifically requesting an User object which has name property set to test from the query, it queries the DB(ignoring caching mechanism), map resultset to entity object, load them in entity manager and return the array of entity object[s] if any data found. So there is no involvement of entity manager here. Things would be different if you used find($id) instead of findBy() because now Doctrine will check entity manager first, query DB if not found.

Mun Mun Das
  • 14,992
  • 2
  • 44
  • 43
0

$result2

This returns an array that holds all entities with test as name:

$result2 = $em->getRepository('UserEn')->findBy(array('name'=>'test'));

In order to get only one record you should use findOneBy instead of findBy:

$result2 = $em->getRepository('UserEn')->findOneBy(array('name'=>'test'));

$result3

In the $result3 you should call $q->getSingleResult() instead of $q->getResult():

$result3 = $q->getSingleResult();
manix
  • 14,537
  • 11
  • 70
  • 107
  • When I tested it with findOneBy, I received: No result was found for query although at least one row was expected. Implying that 'findBy' finds also no object. With getSingleResult: No result was found for query although at least one row was expected. Also meaning that 'getResult' would find no object either. – user1592714 Sep 23 '12 at 03:26
  • What's funny is "$result1 = $em->find('UserEn', 'test');" works. $result1: UserEn object { *User*name => (string) test *User*regist => null *User*con => (int) 0 *User*last => DateTime object { date => (string) 1990-01-01 00:00:00 timezone_type => (int) 3 timezone => (string) Europe/Berlin } – user1592714 Sep 23 '12 at 03:36
  • @user1592714, if you used `$em->find('UserEn', 'test')` and it works... looks like the `name` is the primary key. :s – manix Sep 23 '12 at 04:30