3

What is the cleanest way of using the Doctrine findBy methods but getting an array returned and not objects.

Doctrine::getTable('Table')->findOneById(x);

That works but returns a doctrine object.

I'd still like to be able to use the find methods but I know I can't add

->fetchArray()

on the end.

Anyone else had this problem?

4 Answers 4

20

You can specify the hydration mode when using magic finders, like so:

Doctrine_Core::getTable('Table')->findOneById($x, Doctrine_Core::HYDRATE_ARRAY);
Sign up to request clarification or add additional context in comments.

Comments

3

Try use toArray

Doctrine::getTable('Table')->findOneById(x)->toArray();

1 Comment

If you do this, you will first fetch an object and then convert it to an array, which is not efficient memory-wise.
3

Haim Evgi and DuoSRX's answers are correct, but there's a slightly different version for both that I prefer when using Symfony:

Let's say your model name is Person, you would use:

PersonTable::getInstance()->findOneById(x)->toArray();

or

PersonTable::getInstance()->findOneById($x, Doctrine_Core::HYDRATE_ARRAY);

2 Comments

So what is the difference ?
@NBPalomino: The first one retrieves the full Object and converts it to an Array, the second one retrieves it directly as an Array (which uses less memory and is faster). I'd advice to use Array Hydration whenever you need to retrieve information without updating the database.
1
$adCampaign = $em->createQuery('select c from \Model\Campaign c where c.client = ?1')
->setParameter(1, $clientId)
->getArrayResult();

where em is the entityManager - you get the result as array with getArrayResult

1 Comment

I think you'll find your answer relates to Symfony 2.x (Doctrine 2) which supports namespaces and the entity manager service, whereas the original question is tagged Symfony 1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.