Welcome Guest, Not a member yet? Register   Sign In
Documentation suggestion - CI3 query builder
#1

This bit me today so I figured it might be worth sharing.

The order in which you call methods in the query builder generally doesn't matter UNLESS you are using table aliases and table prefixes.

Here's a quick example, using a table prefix "ff_" :

PHP Code:
$this->db->select('C.contact_id');
$this->db->join('contact_meta as M''C.contact_id = M.contact_id''LEFT');
$this->db->from('contact as C'); 

Because the FROM is called after the JOIN, the alias is not tracked, so the SQL ends up as follows:

Code:
SELECT ff_C.contact_id
LEFT JOIN `ff_contact_meta` as `M`
ON `ff_C`.`contact_id` = `M`.`contact_id`

Note the erroneous ff_C prefix in the join - the alias 'C' was not tracked when the join SQL was created, so the table prefix was applied in the wrong place.

Placing the FROM call prior to the JOIN resolves this.

Might be worth either updating the docs to reflect this (if it's not considered a bug, that is).
Reply
#2

Well, it's not a bug (there's just no sane way to make that work), but it's also not a recommended practice to make such calls in order different from the SQL language, even if it would work in most cases with CI.

I'd put a note about this in the docs, but I'm not really sure where the appropriate place for that would be ... under the from() description? Under join()? select()? A separate section about it perhaps? Should it be about aliasing alone (I believe it affects more than that)? For an addition to the documentation to be useful, all of these questions need to be answered. If you can figure it out, please submit a pull request to our GitHub repo with your suggested changes.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB