Showing posts with label Doctrine2. Show all posts
Showing posts with label Doctrine2. Show all posts

Tuesday, 23 April 2013

Getting "Must be a StateFieldPathExpression" Symfony2/Doctrine exception

Problem:

I'm getting a weird error when making a DQL query in my Symfony2 project. The error contains the phrase "Must be a StateFieldPathExpression". This seems to happen with queries that try to select an identity field (or something with a foreign key.)

Solution:

This may be a bit of a work around, but you can try using the IDENTITY() function in the DQL query to get the id. For instance, imagine that you wanted to select an external ID (un-creatively named 'extern_id'), among other (more un-creatively named) fields:

$dql = "
SELECT IDENTITY(s.extern_id) AS eid, 
  s.some_col AS sc,
  s.another  AS ac
FROM something s WHERE 1";

$em->createQuery($dql);

// ... etc ...

Notes:

This was tested to work using up to Symfony 2.1.4-DEV.

This workaround seems to work for now. If there's anyone out there with more knowledge of Doctrine and DQL, here's a question for you: is using IDENTITY() the right way to go on a permanent basis?

Saturday, 14 April 2012

Native SQL with Doctrine2 Fixtures in Symfony2

Sometimes the use of native SQL queries is desired over using Doctrine2 when programming fixtures in Symfony2, whether this be for performance reasons, etc. While it's recommended to use Doctrine2 in most cases, here's how to execute a SQL query:

$manager->exec($yoursql);

Note that this assumes that $manager is an ObjectManager type (hint: it should already be if you're creating your own fixture that extends Doctrine\Common\DataFixtures\AbstractFixture).

Doctrine fixtures is still changing, so I'll note that this works as of April 14, 2012 but it might not if they change their public interface in the future.