How do I translate this raw SQL query in PHP ActiveRecord?

994 Views Asked by At

I'm trying to run this sql query as a php activerecord query:

 delete from article_categories where 
     article_id = 10
 and
     category_id in (1,4,5,6,7)

This statement works fine when I run it from the mysql console.

I tried doing this from php activerecord:

   $query["conditions"] =  array('article_id = ? and category_id in (?)', 10, "1,4,5,6,7");
   ArticleCategory::delete_all($query);

The problem is it is only deleting one record at a time.

I expect all the records that match

   article_id == 3

and

   category_id == 1 || category_id == 2 || ... || category_id == 5

to be deleted.

However only the first record with fields article_id = 3, category_id = 1

gets deleted.

What am I typing wrong?

2

There are 2 best solutions below

3
On

I'm not really sure if the ID you're sending it to delete can be empty? The documentation shows this for "Massive Update or Delete".

  Post::table()->delete(array('id' => array(5, 9, 26, 30));

So, translated in your situation that would be something like

ArticleCategory::delete(array(array('id'        => array(1, 4, 5, 6, 7)),
                              'conditions'=> array('article_id = ?', 10),
                             ));
2
On

If you want to use "IN (?)" in your where clause, be sure to pass an array as the condition value. Otherwise it would just read IN ("1,2,3,4") in stead of IN (1,2,3,4) (note the double quotes in the former version!).

So, it would look something like this:

$article_id = 1;
$categories = array(1, 2, 3, 4);
ModelName::delete_all(array(
    'conditions' => array('article_id = ? and category_id IN (?)', $article_id, $categories)
));

And if you just want to delete the current record, do:

$record->delete();

Be careful not to invoke ->save() afterward, because the record will be saved again.