简体   繁体   中英

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

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?

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.

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),
                             ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM