Martin
Martin

Reputation: 61

doctrine select statement always returns all fields of the table

I have the following table

Test:
    tableName: test
    columns:
        test_id:
            name: test_id as id
            primary: true
            autoincrement: true
            type: integer
            notnull: true
        test_name:
            name: test_name as name
            type: string(255)
        test_title:
            name: test_title as title
            type: string(255)

and this dql statement

$dql = Doctrine_Query::create()->select('t.name')->from('Model_Test t');

the following sql ist generated

SELECT t.test_id AS t__test_id, t.test_name AS t__test_name FROM test t

but after fetching the result in doctrine, I have access to the title field even it is not selected:

foreach ($results as $result) {
    foreach ($result as $filed => $value) {
        echo "$filed => $value <hr>"; // echoes 'title' => null but title in db has other value
    }                                
}                                

also a dump via Zend_Debug::dump($results->toArray()); shows me all fields as if I would have done a select *

So how to limit the returned fields to match my selection?

Thanks in advance

Martin

Upvotes: 3

Views: 3552

Answers (3)

Attila Fulop
Attila Fulop

Reputation: 7011

This one works for me, and only fetches the queried fields:

$events = Doctrine_Query::create()
     ->select("e.id, e.Title, e.Lat, e.Lon, e.Startdate, e.Location, e.Url")
     ->from('Event e')
     ->setHydrationMode(Doctrine::HYDRATE_ARRAY)
     ->execute();

The resulting array will only contain the selected fields

Upvotes: 1

Martin
Martin

Reputation: 61

I guess:

because

$results = $dql->execute();

fetches the result as an object, the non selected vars are filled with nulls

whereas

$results = $dql->fetchArray(); 

fetches an array and in this case only the selected fields appear (besides the primary key)

Upvotes: 3

petraszd
petraszd

Reputation: 4297

I am not sure, but I think doctrine selects just id and name, but when You try to access title it sees that title is not fetched from DB. So doctrine refetches that object (only this time using SELECT * or similar query).

If You have some kind of Doctrine query profiler -- you probably could see all additional queries required in foreach loop.

Just a wild quess, by the way...

Oh, you can use $query->execute(Doctrine::HYDRATE_ARRAY) if you want to select only some portion of fields.

Upvotes: 0

Related Questions