php – Silverstripe – 删除Dataobjects而不是使用自定义sql查
是否有更好的方法删除早于x-days的数据对象而不是使用自定义SQL查询?
这就是我现在所做的 $host = 'localhost'; $username = 'db123'; $password = 'pass'; $db_name = 'db123'; mysql_connect("$host","$username","$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot select DB"); $sql = "DELETE FROM Cart WHERE Created < (CURDATE() - INTERVAL 1 DAY)"; $result = mysql_query($sql); mysql_close(); 解决方法
首先,使用mysql_query是不好的,不仅仅是在这种情况下.
mysql_query已被弃用,不应再使用. 其次,SilverStripe已经有一个DB连接,不要尝试创建另一个. 选项1: 最干净的方法当然是使用SilverStripe ORM. >很容易 它很直接: // to delete all `DataObject`s in a List,just loop it and call ->delete() foreach($list as $item) { $item->delete(); } // there also is a method that does that for you,however,I would advise against it // because it is currently inconsistently implemented and might lead to unexpected results // $list->removeAll(); // i STRONGLY RECOMMEND AGAINST THIS // if $list is a DataList,it will delete all records // if $list is a ManyManyList,it will unlink all records // if $list is a ArrayList,it will error because there is no removeAll() method on ArrayList 解决你的问题: $date = date('Y-m-d H:i:s',strtotime("now -1 day")); $list = Cart::get()->filter('Created:LessThan',$date); foreach($list as $item) { $item->delete(); } 但是,在删除许多DataObjects时,它也有一个主要的缺点:性能. 在SilverStripe文档中了解有关Datamodel / ORM和DataObject的DataList,:: get(),– > filter()和 – > delete()的更多信息 选项2: 如果您真的需要,可以使用较低级别的ORM来执行删除: $query = new SQLQuery(); $query->setDelete(true); $query->setFrom('Cart'); $query->setWhere('Created < (CURDATE() - INTERVAL 1 DAY)"'); // if you want to debug the query,you can use ->sql() to get it as string // echo $query->sql(); $query->execute(); 在SilverStripe docs中阅读有关SQLQuery的更多信息 选项3: 如果您出于某些原因确实想要完全避免使用ORM,SilverStripe还允许您执行原始SQL查询: DB::query("DELETE FROM Cart WHERE Created < (CURDATE() - INTERVAL 1 DAY)"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |