Php Silverstripe—删除数据对象而不是使用自定义sql查询的更好方法
有没有更好的方法来删除早于x天的数据对象,而不是使用自定义sql查询 我现在就是这么做的Php Silverstripe—删除数据对象而不是使用自定义sql查询的更好方法,php,silverstripe,Php,Silverstripe,有没有更好的方法来删除早于x天的数据对象,而不是使用自定义sql查询 我现在就是这么做的 $host = 'localhost'; $username = 'db123'; $password = 'pass'; $db_name = 'db123'; mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_na
$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();
$host='localhost';
$username='db123';
$password='pass';
$db_name='db123';
mysql_connect(“$host”、“$username”、“$password”)或die(“无法连接”);
mysql_select_db($db_name)或die(“无法选择db”);
$sql=“从创建的购物车中删除<(CURDATE()-间隔1天)”;
$result=mysql\u查询($sql);
mysql_close();
首先,使用mysql\u查询是不好的,不仅仅是在这种情况下。
mysql\u query
已被弃用,不应再使用
其次,SilverStripe已经有一个DB connect,不要尝试创建另一个。
SilverStripe提供了许多查询数据库的方法
选项1:
当然,最干净的方法是使用SilverStripe ORM。
DataObject
有一个名为->delete()的方法
与编写自己的SQL查询相比,使用delete有几个优点
- 很容易
- 它将为您从其所有表中删除数据对象(例如数据对象类
文件夹
是文件
的子类,因此如果您执行$myFolder->delete()
操作,它将在文件
表中删除该文件夹
(如果有文件夹
表))
- 它将执行SilverStripe删除钩子(
onBeforeDelete
和onAfterDelete
)
这很直截了当:
// 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();
}
但是,在删除许多数据对象时,它也有一个主要缺点:性能。
但是,如果可以说性能不是大问题,我仍然建议使用->delete()
。好处通常大于缺点
阅读更多关于和的SilverStripe文档中的数据列表
,::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();
thx,我会看看的嗯。。。你为什么不使用SilverStripe的ORM?或者你真的在用SilverStripe?太好了谢谢。我首先想到的是定制sql查询。但这(选项1)要好得多。
DB::query("DELETE FROM Cart WHERE Created < (CURDATE() - INTERVAL 1 DAY)");