Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony/Doctrine: fetching data as object

In Symfony, I use Doctrine_Query to query the database

$q = Doctrine_Query::create()
      ->from('User u')
      ->where('u.username = ?', $username)
      ->andWhere('u.password = ?', $password);
$user = $q->fetchArray();

The problem is that the results are stored in an array. Is there any way that I can make it fetch an object instead of an array?

Also, are there any other ways that I can query the database in Symfony or do I have to use Doctrine's functions?

like image 733
Rain Avatar asked Dec 21 '22 16:12

Rain


1 Answers

You can use

$q->fetchOne()

to fetch one record (object) or

$q->excute()

to fetch a group of objects.

I personally use these almost everytime when I use symfony. sometimes you need to fetch arrays in that case you can use data hydration like HYDRATE_ARRAY or HYDRATE_ARRAY_HIERARCHY if you have a nested set.

As for raw queries check out this: raw sql in doctrine

Edit:

I just had to use raw queries myself and this is how it works in symfony:

$pdo = Doctrine_Manager::getInstance()->getCurrentConnection()->getDbh();
$query = "SELECT name, slug,
     ( 3959 * acos( cos( radians(:lat) ) * cos( radians( lat ) )
      * cos( radians( lng ) - radians(:lng) ) + sin( radians(:lat) )
      * sin( radians( lat ) ) ) ) AS distance
    FROM rss_city WHERE (lat <> :lat and lng <> :lng)HAVING distance IS NOT NULL
    ORDER BY distance LIMIT 5";
$stmt = $pdo->prepare($query);
$params = array(
  "lat"   => $lat,
  "lng"   => $lng
);
$stmt->execute($params);
$results = $stmt->fetchAll();

This query returns an array of the 5 closest cities to our lat / lng coordinates. I think it's self-explanatory.

like image 114
Adam Arold Avatar answered Dec 24 '22 04:12

Adam Arold