Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

symfony - Doctrine won't let me select specific fields

The symfony framework features an app/console file that can be executed via php to perform some maintenance tasks. It allows users to run DQL queries as well:

# php app/console doctrine:query:dql --hydrate=array 
    'SELECT u.id, u.nameFirst, u.nameLast  FROM DatabaseBundle:User u'  
array
  0 => 
    array
      'id' => string '1' (length=1)
      'nameFirst' => string 'jaroslav' (length=8)
      'nameLast' => string 'rakhmatoullin' (length=13)
  1 => 
    array
      'id' => string '2' (length=1)
      'nameFirst' => string 'B?b K?re' (length=10)
      'nameLast' => string 'Ytrefoss' (length=8)

Observe that I selected three specific columns. The problem I'm having is that a similar query gives me an error when two tables are joined.

# php app/console doctrine:query:dql  --hydrate=array 
    'SELECT u.id , r FROM DatabaseBundle:User u JOIN u.roles r'

  [DoctrineORMQueryQueryException]                   
  [Semantical Error] line 0, col -1 near 'SELECT u.id ,': 
     Error: Cannot select entity through identification variables 
     without choosing at least one root entity alias.  

The following returns the whole user joined with his roles:

# php app/console doctrine:query:dql  --hydrate=array 
     'SELECT u, r FROM DatabaseBundle:User u JOIN u.roles r'

Obviously, I'm missing something.

Any ideas? I would appreciate links to appropriate docs too (on this specific matter).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the documentation on "Partial Object Syntax":

By default when you run a DQL query in Doctrine and select only a subset of the fields for a given entity, you do not receive objects back. Instead, you receive only arrays as a flat rectangular result set, similar to how you would if you were just using SQL directly and joining some data.

If you want to select partial objects you can use the partial DQL keyword.

php console doctrine:query:dql --hydrate array 
  'SELECT partial s.{name ,id}, partial c.{name, id } 
   FROM DatabaseBundle:ProductCategories c 
   JOIN c.suppliers s ORDER BY s.name, c.name'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...