Search code examples
phpsqldoctrinedoctrine-1.2dql

How to sort fields of a related (joined) table in query results?


Probably related more to SQL than to Dotrine itself.

I have two tables, specified in schema file roughly like this:

Project:
  columns:
    name: { type: string(255), notnull: true }

Task:
  columns:
    project_id: { type: integer, notnull: true }
    name: { type: string(255), notnull: true }
  relations:
    Project: { onDelete: CASCADE, local: project_id, foreign: id, foreignAlias: Tasks }

I would like to get a project with a list of it's tasks, sorted by the name.

$projectWithTasks = Doctrine_Core::getTable("Project")->createQuery("p")
    ->leftJoin("p.Tasks t")
    ->where("p.id = ?", $projectId)
    ->orderBy("t.name ASC")
    ->fetchOne();

Obviously, it won't work. I was searching for a solution for quite some time, but probably I am using the wrong words, because I couldn't find any useful information. I would be very grateful for any help.


Solution

  • You can define the default order for Tasks as relation of Projects in your YML file, e.g.:

    Project:
      columns:
        name: { type: string(255), notnull: true }
      relations:
        Task:
          local: id
          foreign: project_id
          orderBy: name
    
    Task:
      columns:
        project_id: { type: integer, notnull: true }
        name: { type: string(255), notnull: true }
    

    This way your tasks are automatically sorted by name when gotten through Project.