简体   繁体   中英

phalcon MVC model how can delete data?

delAction

I am searching for a long time on.net, but no luck. Please help or try to give some ideas how to achieve this.

I want to delete some data like:

$articleIds = '1,2,3,5,8';
$User    = new User();
$success = $User->delete($articleIds);  

But, that gives an error. What should I do?

Thanks in advance.

Try any of the following ways of deleting multiple records, and pick the one you like the best:

A) Finding then deleting:

$ids = '1,2,3';
$records = User::find(sprintf("id IN (%s)", $ids)); // or you can avoid using sprintf and simply use concatenating operator like "IN (" . $ids . ")"
$records->delete(); // this should return boolean

B) You can also chain the above method calls:

User::find(sprintf("id IN (%s)", $ids))->delete();

C) Or you can iterate each record and then delete it, like shown in the Phalcon documentation: https://docs.phalconphp.com/en/3.2/db-models#delete-records

D) Or finally, you can write a 'raw' SQL statement using Phalcon PHQL:

$config = [
    'host' => '127.0.0.1',
    'username' => 'user',
    'password' => 'pass',
    'dbname' => 'test'
];
$connection = new \Phalcon\Db\Adapter\Pdo\Mysql($config);
$sql = sprintf("DELETE `users` WHERE `id` IN (%s)", $ids);
$success = $connection->execute($sql);

More info here: https://docs.phalconphp.com/en/3.2/db-layer#crud


And remember... be very very careful with accepting record ids from user input (examples: via GET, or from a form/table that allows the user to select records). But I think this is a topic for another question.

First sanitize your input and make sure that only int variables are accepted into your array of ids. After that use the following code and delete all your records.

$ids = [1, 2, 3];
$records = User::find([
    'conditions' => 'id IN (:ids:)',
    'bind' => array('ids' => implode(', ', $ids)),
]);
$records->delete();
$models = VoucherThemeModel::find([
  'conditions' => 'voucher_theme_id IN ({ids:array})',
  'bind' => ['ids' => $voucher_ids]
]);

$models->delete();

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