Welcome Guest, Not a member yet? Register   Sign In
Easy ActiveRecord questions
#1

[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?
#2

[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');
#3

[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');
#4

[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.
#5

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

[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.




Theme © iAndrew 2016 - Forum software by © MyBB