加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – Silverstripe – 删除Dataobjects而不是使用自定义sql查

发布时间:2020-12-13 22:10:58 所属栏目:PHP教程 来源:网络整理
导读:是否有更好的方法删除早于x-days的数据对象而不是使用自定义SQL查询? 这就是我现在所做的 $host = 'localhost'; $username = 'db123'; $password = 'pass'; $db_name = 'db123'; mysql_connect("$host","$username","$password")or die("cannot connect");
是否有更好的方法删除早于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连接,不要尝试创建另一个.
SilverStripe提供了许多查询数据库的方法.

选项1:

最干净的方法当然是使用SilverStripe ORM.
DataObject有一个名为 – > delete()的方法.
使用delete比编写自己的SQL查询有几个优点.

>很容易
>它会从你的所有表中删除DataObject(例如DataObject类Folder是File的子类,所以如果你执行$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();
}

但是,在删除许多DataObjects时,它也有一个主要的缺点:性能.
但是,如果您可以说性能不是一个大问题,我仍然会建议使用 – > delete().好处通常大于缺点.

在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)");

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读