Search code examples
doctrinedql

A simple innerJoin Doctrine Query


I tried to generate a simple SQL select:

SELECT c.com_id, c.pro_id, c.com_nombre 
FROM bd_fn.fn_comuna c  
inner join bd_fn.fn_provincia p 
on (c.pro_id = p.pro_id) 
where p.pro_nombre = 'namepro';

But the DQL throw this error:

Doctrine_Table_Exception' with message 'Unknown relation alias fn_provincia.

The doctrine version is 1.XX, the persistence was create by Visual Paradigm. The DQL is this:

$q = Doctrine_Query::create()
    ->select('c.com_id')
    ->from('fn_comuna c')
    ->innerJoin('c.fn_provincia p')
    ->where('p.pro_nombre=?',$namepro);

the class fn_comuna.php

<?php
/**
 * "Visual Paradigm: DO NOT MODIFY THIS FILE!"
 * 
 * This is an automatic generated file. It will be regenerated every time 
 * you generate persistence class.
 * 
 * Modifying its content may cause the program not work, or your work may lost.
 */

class Fn_comuna extends Doctrine_Record {
  public function setTableDefinition() {
    $this->setTableName('bd_fn.fn_comuna');
    $this->hasColumn('com_id', 'integer', 4, array(
        'type' => 'integer',
        'length' => 4,
        'unsigned' => false,
        'notnull' => true,
        'primary' => true, 
        'autoincrement' => false,
      )
    );
    $this->hasColumn('pro_id', 'integer', 4, array(
        'type' => 'integer',
        'length' => 4,
        'unsigned' => false,
        'notnull' => true,
      )
    );
    $this->hasColumn('com_nombre', 'string', 100, array(
        'type' => 'string',
        'length' => 100,
        'fixed' => false,
        'notnull' => true,
      )
    );
  }

  public function setUp() {
    parent::setUp();
    $this->hasOne('Fn_provincia as pro', array(
        'local' => 'pro_id', 
        'foreign' => 'pro_id'
      )
    );
    $this->hasMany('Fn_institucion as fn_institucion', array(
        'local' => 'com_id', 
        'foreign' => 'com_id'
      )
    );
    $this->hasMany('Fn_replegal as fn_replegal', array(
        'local' => 'com_id', 
        'foreign' => 'com_id'
      )
    );
  }

}

?>

Solution

  • As you can see from your model class, the relation between fn_comuna & fn_provincia is called pro.

    $this->hasOne('Fn_provincia as pro', array(
        'local' => 'pro_id', 
        'foreign' => 'pro_id'
      )
    );
    

    So you have to use this name when you deal with join:

    $q = Doctrine_Query::create()
        ->select('c.com_id')
        ->from('fn_comuna c')
        ->innerJoin('c.pro p')
        ->where('p.pro_nombre=?', $namepro);