Symfony / Doctrine: fetching data as an 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 a way I can get it to retrieve an object instead of an array?

Also, are there other ways in which I can query the database in Symfony or do I need to use the Doctrine functions?

+4
source share
1 answer

you can use

 $q->fetchOne() 

to retrieve a single record (object) or

 $q->excute() 

to get a group of objects.

I use them almost every time I use symfony. sometimes you need to take arrays, in which case you can use data hydration, for example HYDRATE_ARRAY or HYDRATE_ARRAY_HIERARCHY, if you have a nested set.

Regarding raw queries, check this out: raw sql in the doctrine

Edit:

I just needed to use raw requests, and here 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 nearest cities to our lat / lng coordinates. I think this is self-evident.

+11
source

Source: https://habr.com/ru/post/1344235/


All Articles