Welcome Guest, Not a member yet? Register   Sign In
Active Record method chaining - doesn't work with update?
#1

Already posted to SO, but thought I might as well try at Mecca as well.

I'm trying to use Active Record methods to update a table and flag a task as complete like this:

$this->db->update('tasks', array('status' => 'complete'))
->where('id', $task_id);

But it's giving me an error:

Call to a member function where() on a non-object

Is there something wrong here that I can't see here? or does method chaining not work with update? The docs are pretty thin on method chaining..

It does work if I break it into two lines...

$this->db->where('id', $task_id);
$this->db->update('tasks', array('status' => 'complete'));
but shouldn't method chaining work here?

PHP version: 5.5.4 CI version: 3
Reply
#2

The update method works like described here

http://www.codeigniter.com/userguide3/da...ght=update

For e.g. in your case you can write this:

$this->db->update('tasks', array('status' => 'complete'), array('id' => $task_id));

Reply
#3

Hello whiteatom,

Rufnex is right, but I use a lot chaining for complex update queries at work and I tell it to you : it works Smile

You tried to chain the where clause after the update clause, try to switch them and you'll see !

Happy coding with CI !
Reply
#4

update() and insert(), and probably a few others, execute the compiled query at that point. So you need to have all of your wheres/selects/etc before calling those action methods.
Reply
#5

The following methods do not return $this, so another db method can not be used after them in a chain:
count_all_results()
dbprefix()
delete()
empty_table()
get()
get_compiled_delete()
get_compiled_insert()
get_compiled_select()
get_compiled_update()
get_where()
insert()
insert_batch()
replace()
set_dbprefix()
truncate()
update()
update_batch()

Additionally, reset_query() returns $this and therefore can be chained, but it will reset your query, so it's more likely to be useful at the beginning of a chain than the end...
Reply
#6

(02-25-2015, 12:32 PM)CroNiX Wrote: update() and insert(), and probably a few others, execute the compiled query at that point. So you need to have all of your wheres/selects/etc before calling those action methods.

This is the problem with "thin documentation" in the chaining. The example shows select()->where(), so the logical extension would be update()->where(). Now I have this info, I can use this properly.

Thanks for your help guys, I will certainly come here before SO now because I have no response in 20-odd hours over there. Pretty rare to stump the Stack crowd.

Cheers,

whiteatom
Reply




Theme © iAndrew 2016 - Forum software by © MyBB