Welcome Guest, Not a member yet? Register   Sign In
deleting using active records
#1

[eluser]timaksu[/eluser]
ive got a small problem guys. i am pretty sure its possible with something like join...anyway

i have an array of id's (int) for blog posts..each with comments.

i want to remove each blog post and their comments. comments and posts are in different tables. comments are linked to the corresponding post through the post id. (a field called "post_id" in the comment table contains the id of the post. posts are in the post table).

i foreach through the array of id's..

Code:
foreach($id as $i){
//check if this value is an integer
if(is_int($i)){
  $this->db->where('id',$id);
  $this->db->delete('post');
                            
  $this->db->where('post_id',$id);
  $this->db->delete('comment');
}
//error if it isnt
else{
  show_error('Value in Post Id array was not an integer');
}
}

now this would work fine, but what if we had an array with a letter or something else in the middle of it. it'll delete everything before it got to the letter, throw an error at the letter and ignore the rest of the array..

i can solve this IF there was no extra table. i'd simple move the delete part after the foreach loop.

Code:
foreach($id as $i){
//check if this value is an integer
if(is_int($i)){
  $this->db->where('id',$id);
}
//error if it isnt
else{
  show_error('Value in Post Id array was not an integer');
}
}
$this->db->delete('post');
then that would work fine. if an error came up, no harm done...

i dont know how to do this with 2 tables.

ADDED:

this is still WIP so i havnt actually tested this. but ive just noticed this:

Code:
$this->db->where('id',$id);
  $this->db->delete('post');
                            
  $this->db->where('post_id',$id);
  $this->db->delete('comment');

is that the equivalent of..
DELETE FROM post WHERE id = $id
and then
DELETE FROM comment WHERE post_id = $id

or is it the equivalent of..
DELETE FROM post WHERE id = $id
and then
DELETE FROM comment WHERE id = $id AND WHERE post_id = $id

hope you guys can get around to both questions!
#2

[eluser]WanWizard[/eluser]
As to your last question: any command that runs a query resets the query parameters.

So
DELETE FROM comment WHERE id = $id AND WHERE post_id = $id

should be coded as:
Code:
$this->db->where('id',$id);
$this->db->where('post_id',$id);
$this->db->delete('comment');
#3

[eluser]timaksu[/eluser]
oh alright good. i couldnt find anything that said it reset in the guide though. it may have just been because i missed maybe.. i was assuming that it reset after i ran the query anyway. (i was after

DELETE FROM post WHERE id = $id
and then
DELETE FROM comment WHERE post_id = $id

thats why i coded like i did. turns out it was correct Smile )




Theme © iAndrew 2016 - Forum software by © MyBB