I'm using CodeIgniter's Active Record Classes and I'm retrieving an error using the following code:
$this->db->select("*");
$this->db->order_by("id");
$this->db->limit($limit, $offset);
$this->db->from("atoms");
$this->db->join("atommeta", "atommeta.atom_id = atoms.atom_id");
$query = $this->db->get();
It produces this error:
Error Number: 1052
Column 'id' in order clause is ambiguous
SELECT * FROM (`atoms`) JOIN `atommeta` ON `atommeta`.`atom_id` = `atoms`.`atom_id` ORDER BY `id` LIMIT 10
Filename: /Applications/MAMP/htdocs/atom/models/atom_model.php
Line Number: 197
Line 197: $query = $this->db->get();
Any ideas as to why? It seems to be something to do with the order_by
The error means that you are trying to order by a column name that is used in more than one table. Update your order_by statement with the name of the table that has the column you want to order by. For example:
$this->db->order_by('atoms.id');
It looks like there is an id column in both your atommeta and atoms tables. Because you are joining these tables you will need to specify what column you want to order by.
You will want
$this->db->order_by("atoms.id");
or
$this->db->order_by("atommeta.id");
You should specify which table that 'id' belogns to.
$this->db->select("*");
$this->db->from("atoms");
$this->db->join("atommeta", "atommeta.atom_id = atoms.atom_id");
pick one:
$this->db->order_by("atommeta.id");
or
$this->db->order_by("atoms.id");
Related
I can't seem to get this working and it's driving me nuts.
I'm using CodeIgniter's Ignited Datatables library I found on github
I have the below method for getting records from a table joined to another:
public function get_templates_ajax() {
$this->datatables->select('tem.template_id, tem.name, tem.vat, COUNT(itm.template_id) AS total_items');
$this->datatables->from('templates tem');
$this->datatables->join('items itm', 'tem.template_id = itm.template_id', 'left');
$this->datatables->where('tem.user_id', $this->session->user_id);
$this->datatables->group_by('tem.template_id');
$this->datatables->add_column('actions', 'EditDelete', 'tem.template_id, tem.name, tem.vat');
return $this->datatables->generate();
}
Yes, I have a field named user_id in both tables, but I'm not selecting the column, however, I get this error: Duplicate column name 'user_id'.
I specified the columns I want selected as seen below:
$this->datatables->select('tem.template_id, tem.name, tem.vat, COUNT(itm.template_id) AS total_items');
I know if I wanted to select the user_id column, I'd use an alias, but I'm not selecting it.
Doing $this->db->last_query(); dumped this SQL:
SELECT COUNT(*) FROM (SELECT * FROM `templates` `tem` LEFT JOIN `items` `itm` ON `tem`.`template_id` = `itm`.`template_id` WHERE `tem`.`user_id` = '1' GROUP BY `tem`.`template_id`) SqueryAux
So it seems that the select method is being ignored while it is selecting all columns from both tables.
What could I be doing wrong?
After much digging, I solved the problem by making some adjustments to the library.
Apparently, the problem was originating from the get_total_results(); method in the class, more specifically these 2 line:
$subquery = $this->ci->db->get_compiled_select($this->table);
$countingsql = "SELECT COUNT(*) FROM (" . $subquery . ") SqueryAux";
The subquery variable was selecting all columns from the main table and joined tables using dear old *.
Here is what I did to fix the problem:
I replaced the $subquery line with this:
....
//ensure table with alias does not contain more than 1 space between original table name and alias
$this->table = preg_replace('!\s+!', ' ', $this->table);
$tbl = explode(" ", $this->table);
//if table has alias, get it, else get table name
$table = count($tbl) > 1 ? $tbl[1] : $tbl[0];
$subquery = $this->ci->db->get_compiled_select($this->table);
//prefix table/alias to * so it selects columns from the main table only
$subquery = str_replace("*", "{$table}.*", $subquery);
....
Hope it helps someone.
I have 4 records on my guests database.
I'm trying to query to the guest that has note_display = 1 and have the highest id.
I've tried
$last_note = DB::table('guests')->where('note_display','=',1)->where('id', DB::raw("(select max(`id`) from guests)"))->first();
I got
Trying to get property of non-object
I'm a lil stuck now, any hints will be a huge helps ?
There is no need to use raw in this query. You can run a simple query like
Guest::where('note_display', 1)->orderBy('id', 'desc')->first();
And it will return the Guest with the highest ID and having note_display = 1.
The raw sql string should be something like SELECT * FROM guests WHERE note_display = 1 ORDER BY id DESC LIMIT 1 it looks you are getting only rows with note_display = 1 inside a sub-query WHERE id={the maximum id present in the table}
It select the maximum of id where the the note_display is = 0, so the try to get non-object error happened.
If you're insisting to go with raw try this!
$last_note = DB::table('guests')->where('id', DB::raw("(select max(`id`) from guests where note_display = '1')"))->first();
can you help I have two tables images and note. I would like to get all items from these tables and order by date. It is possible I am using active record in codeigniter. Tables are independent.
Thank you for replies.
this should work:
$this->db->orderby("date", "ASC"); //or desc
$query = $this->db->get('images'); //or $query = $this->db->get('note');
$result=$query->result_array();
print_r($result);
or if you want use union all
$this->db->query('SELECT * FROM (SELECT id, date FROM images UNION ALL SELECT id, date FROM note) result ORDER BY result.date');
Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order from http://www.w3schools.com/sql/sql_union.asp.
I think you want a Cross Join.
Here is your codeigniter code
$this->db->from("images ,note");
$this->db->select("images.*,note.*);
//make sure both dont have same column name other wise use this
//$this->db->select("images.column1,images.column2,note.column1);
$this->db->orderby("images.date", "DESC");
//you can add more orderby
//you can add where condition too
$result=$this->db->get()->result_array();
Now you will get the cross product.
Hope it will help you.
In which table do you have date column? I assume you have it in images table.
$this->db->select('images.coulmn1, images.culmn2, images.date_col, note.col1, note.col2');
$this->db->from('images');
$this->db->join('note', 'note.key1 = images.key1); //key1 is key field to relate both table.
$this->db->order_by("images.date_col", "desc");
$result = $this->db->get()->result_array();
Hope it will help.
Try this:
$this->db->select('*');
$this->db->from('images');
$this->db->join('note');
$this->db->orderby("date column name", "ASC");
$query = $this->db->get();
$result=$query->result_array();
print_r($result);
I have two tables 'accounts_transactions' and 'accounts_bills_transactions'.
I have to left join these two using active record of codeigniter.But the names of key columns used to join are different.So I am not getting the key column from the left table in the output .What query should I write to get the key column from the left table included in the result.
My code is
$this->db->select('*');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_bills_transactions.transaction_id','left');
$query = $this->db->get();
So, as you see the key columns used to join here are , id from left table and transaction_id from second table.The problem is that I am not getting the id from left table in the result.But I am getting all other columns.I assume the problem is because of difference in column names used to join.ie both the column names are not named 'id' .So how can I get the id from left table included in the result.
You could alias them:
$this->db->select('accounts_transatctions.*, account_transactions.id AS a_id,
accounts_bills_transactions.*,
account_bills_transactions.id AS ab_id');
$this->db->from('accounts_transactions');
$this->db->join('accounts_bills_transactions', 'accounts_transactions.id = accounts_transactions.transaction_id','left');
$query = $this->db->get();
The two IDs will now be available as a_id and ab_id (or whatever alias you choose)
Note: I'm not sure if you can alias in AR without avoiding escaping (haven't been using CI for a while). Should you get any error for that reason, just pass false as second parameter of $this->db->select():
$this->db->select('...', false);
you can try this if you confuse of using $this->where or $this->join
$query = $this->db->query("select ......");
return $query;
You problem is so simple. You can use this query
$query = $this->db
->select('at.*')
->select('abt.id as abt_id');
->from('accounts_transactions at');
->join('accounts_bills_transactions abt', 'at.id = abt.transaction_id','left');
->get()
->result();
When same column are used in join it selects only one. You need to give alise to the other column in second table. The best practice is to use a structure like this
accounts_transatctions
--------------------------
accounts_transatctions_id
other_columns
accounts_bills_transactions
---------------------------
accounts_bills_transactions_id
accounts_transatctions_id
other_columns
I have this structure of the tables:
Table Name: collisions
Fields: id, creator1, creator2
(1, 1, 2) - simple data in my sql table
Table Name: creators
Fields: id, artistname
(1, john smith)- simple data in my sql table
(2, steven michael)- simple data in my sql table
What i need is to join these tables so i can get the artist name instead of creator1 id and creator 2 id.
This is what I have done so far:
$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = cr1.id AND collisions.creator2 = cr2.id', 'left');
$data = $this->db->get('collisions')->result();
but I am getting this error:
Unknown column 'cr1.id' in 'on clause'
SELECT `collisions`.*, `creators`.`artist_name` AS cr1, `creators`.`artist_name` as cr2 FROM (`collisions`) LEFT JOIN `creators` ON `collisions`.`creator1` = `cr1`.`id` AND collisions.creator2 = cr2.id
Can someone tell me what I am doing wrong?
This did the job
$this->db->select('collisions.*, cr1.artist_name as cr1, cr2.artist_name as cr2');
$this->db->join('creators AS cr1', 'collisions.creator1 = cr1.id', 'left');
$this->db->join('creators AS cr2', 'collisions.creator2 = cr2.id', 'left');
$data = $this->db->get('collisions')->result();
Please use actual table name instead of alias :
$this->db->select('collisions.*, creators.artist_name AS cr1, creators.artist_name as cr2');
$this->db->join('creators', 'collisions.creator1 = creators.id AND collisions.creator2 = creators.id', 'left');
$data = $this->db->get('collisions')->result();
the reason why you cant use alias is that the execution of sql is in the following order:
1)FROM clause
2)WHERE clause
3)GROUP BY clause
4)HAVING clause
5)SELECT clause
6)ORDER BY clause
since you were using alias which is created in select clause which executes after where clause.
That's why you can not use the alias that which does not exits.