CodeIgniter Forums
Easy ActiveRecord questions - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Easy ActiveRecord questions (/thread-15948.html)



Easy ActiveRecord questions - El Forum - 02-19-2009

[eluser]coding_hero[/eluser]
Ok, this is my first CI app, so this is a pretty simple question:

If I do a JOIN on two tables, and both have a field name in common (and it is not the field being joined on), how is that returned in the result?

For example:
Code:
$this->db->from ('user_access');
            $this->db->join ('collection',
                             'user_access.collection_id = collection.id');
            $this->db->where ('user_id', $user_id);
            $query = $this->db->get ();
If both 'user_access' and 'collection' have a field named 'name', and you accessed 'name' in $query->result(), which would you get? Is there any way to get the other?


Easy ActiveRecord questions - El Forum - 02-19-2009

[eluser]TheFuzzy0ne[/eluser]
As far as I know, one field will overwrite another by the same name. To avoid this, alias your select fields:
Code:
$this->db->select('field1, field2, collection.name AS cname, useraccess.name AS uname');



Easy ActiveRecord questions - El Forum - 02-19-2009

[eluser]Armchair Samurai[/eluser]
Use aliases and always be specific which columns you are calling. For example
Code:
$this->db->select('u.foo, c.foo AS collection_foo');
$this->db->join('collection c', 'u.collection_id = c.collection.id');
$this->db->where('u.user_id', $user_id);
$query = $this->db->get('user_access u');



Easy ActiveRecord questions - El Forum - 02-19-2009

[eluser]darkhouse[/eluser]
I don't think it "overwrites" anything. My experience has always been that it throws an error stating ambiguous columns. Either way, using aliases is the way to go.


Easy ActiveRecord questions - El Forum - 02-20-2009

[eluser]TheFuzzy0ne[/eluser]
Not when you call them with:
Code:
$this->db->select('*');



Easy ActiveRecord questions - El Forum - 02-20-2009

[eluser]darkhouse[/eluser]
Ah yes, thinking about it now, my queries are always like $this->db->select("id, name, etc"); and that's when I get the ambiguous error, if I'm joining something, but I haven't had that error in a long time as I use aliases for everything that has a duplicate field name.