【问题标题】:Silverstripe bulk save all dataobjectsSilverstripe 批量保存所有数据对象
【发布时间】:2013-04-03 22:06:53
【问题描述】:

我已将 URLSegments 添加到 DataObjects(产品),因此我可以将 ProductName 显示为 URL....代码工作正常:

public function onBeforeWrite(){
    if($this->Name){
        $this->URLSegment = SiteTree::GenerateURLSegment($this->Name);
        if($object = DataObject::get_one($this->ClassName, "URLSegment='".$this->URLSegment."' AND ID !=".$this->ID)){
            $this->URLSegment = $this->URLSegment.'-'.$this->ID;
        }
    } else {
        $this->URLSegment = SiteTree::GenerateURLSegment($this->ClassName.'-'.$this->ID);
    }
    parent::onBeforeWrite();
}

但是,我有超过 1000 个产品...有没有办法在代码中为所有产品数据对象生成批量保存(即一次性),这样我就不必通过 CMS 手动保存每个? ?

【问题讨论】:

    标签: silverstripe


    【解决方案1】:

    只需创建一个带有索引函数的控制器并使用或多或少相同的代码。

    <?php
    
    class UpdateProducts extends Controller {
        public function index() {
    
            $products = DataObject::get('Products');
    
            foreach ($products as $product) {
    
                if (!$product->URLSegment) {
                    $product->write();
                }
            }
        }
    }
    

    然后你可以在浏览器http://example.com/UpdateProducts调用一次函数

    这不是超级有效,所以它真的只是一次性的。如果脚本超时,您可以再次运行它,因为其中的 if 语句意味着只有没有 URLSegment 的产品才会被更新。

    【讨论】:

      【解决方案2】:

      我开始实现 drzax 解决方案,然后找到了这个,它将它作为一个任务来实现。创建此任务是为了将 URLSegments 添加到产品中,因此非常适合我的需求...

      http://www.balbuss.com/creating-tasks/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多