views:

87

answers:

1

I'm confused about how DQL works, and really need some help here.

I have three tables, called "Band", "Agent", and "BandAgent".

BandAgent is the middle table for a Many-to-many relationship, containing agent_id and band_id.

How can I retrieve all Agents related to a specific band_id using a DQL statement?


EDIT

This code works, but I don't know if it is the right way to do it. Echos to the screen all associated Agents related to a Band by BandID:

//$band is a Band Table Row
$bandAgentTable = Doctrine_Core::getTable('BandAgent');
$agentTable = Doctrine_Core::getTable('Agent');

$bandAgentTable = $bandAgentTable->findByBandId($band->getId());
foreach ($bandAgentTable as $bandAgent) {   
    $agent = $agentTable->findById($bandAgent['agent_id']);
    echo $agent[0]['name'];
}

EDIT 2

I ended up reading a heck of a lot about Doctrine, and ended up moving away from Magic Finders. The following code is what I ended up doing for my Many-to-Many issue, if anyone is interested:

public function getRelatedAgents() {
$q = Doctrine_Query::create()
   ->from('Band b')
   ->leftJoin('b.Agents a')
   ->where('b.id = ?', $this->getId());
$bands = $q->fetchArray();
return $bands[0]['Agents'];
}
+3  A: 

Doctrine offers Magic Finders.

$bandAgentTable = Doctrine_Core::getTable('BandAgent');    
$bandAgentTableSearch = $bandAgentTable->findByBand($band);

This will search the column Band in the table BandAgent and match it with the variable $band.

The basic pattern for the finder methods are as follows: findBy%s($value) or findOneBy%s($value). The %s can be a column name or a relation alias. If you give a column name you must give the value you are looking for. If you specify a relationship alias, you can either pass an instance of the relation class to find, or give the actual primary key value.

Update: In response to your edit, you can also search on two columns together.

$agent = $bandAgentTable->findByBandIdAndId($band->getId(), $bandAgent['agent_id']);
Ashish
In order to get it to work with Magic Finders, I had to do two finds in order to get the Many-to-Many relationship joined together. I posted my code in my question above, maybe you can give me on feedback on what I am doing wrong here.
Jon
Whoops! I had read your code wrong. Yeah, that is the way you can go about it. You have information you have in two tables and the only way both those tables are related are via another third table. Hence you have to query all three tables, as far as I can think with an empty stomach.
Ashish
That still only returns a row from the bandAgent table, which is a joining table between Band and Agent. I need to retrieve the Agent name from the Agent table, as an end result. I am accepting your answer, since you ultimately made me solve my issue. I am just not sure if I did it correctly.
Jon
Sorry about the old comment. Had misread the code. I've updated the comment.
Ashish