views:

259

answers:

1

Hello. I'm working on an Active Record pattern (similar to RoR/Cake) for my Zend Framework library. My question is this: How do I figure out whether a select object is using an alias for a table or not?

$select->from(array("c" => "categories"));

vs.

$select->from("categories");

and I pass this to a "fetch" function which adds additional joins and whatnot to get the row relationships automatically...I want to add some custom sql; either "c.id" or "categories.id" based on how the user used the "from" method.

I know I can use

$parts = $select->getPart(Zend_Db_Select::FROM);

to get the from data as an array, and the table name or alias seems to be in "slot" 0 of said array. Will the table name or alias always be in slot zero? i.e. can I reliably use:

$tableNameOrAlias = $parts[0];

Sorry if this is convolute but hope you can help! :)

+1  A: 

Logically, I would think that's how it should work. To be on the safe side, build a few dummy queries using a Select() and dump the part array using print_r or such.

I just performed this test, the alias is the array key, it is not a zero-based numeric array:

   $select = $this->db->select()->from(array("c" => "categories","d" => "dummies"));
   $parts = $select->getPart(Zend_Db_Select::FROM);
   echo '<pre>';
   print_r($parts);
   echo '</pre>';

Output:

Array
(
    [c] => Array
        (
            [joinType] => inner join
            [schema] => 
            [tableName] => categories
            [joinCondition] => 
        )

)

So you would need to reference it as $part["c"]

karim79
Hmm, that's neat, but my issue is I don't know whether the user will pass a select object with an aliased table or just the table name, so I can't reference it like $part["c"]. Maybe I can just grab the [c] by using php's key($array)?
Typeoneerror
Nice, yeah! I think this is getting somewhere.$parts = array("c" => array("tableName" => "categories"));echo key($parts);Gives me the alias name. Just need to loop through the from parts then and grab the keys and use those. Thanks for your help!
Typeoneerror