【问题标题】:SilverStripe duplicate entries even with unique indexSilverStripe 重复条目,即使具有唯一索引
【发布时间】:2016-09-22 02:08:51
【问题描述】:

在使用以下索引在我的 CRM 中添加客户记录时,我试图防止重复记录:

private static $indexes = array(
    'IndexFirstSurName' => array(
        'type' => 'unique', 
        'value' => '"FirstName","Surname"'
    )
);

请注意,我从 Member 扩展了 Customer,其中 FirstNameSurname 来自:

class Customer extends Member 

但 SilverStripe 仍然允许 FirstNameSurname 组合的重复条目?有没有人遇到过同样的问题?

【问题讨论】:

    标签: sql orm silverstripe


    【解决方案1】:

    根据我的经验,即使使用索引,仍然需要 validate():

    public function validate() {
        $result = parent::validate();
    
        if(Member::get()->filter(array('FirstName' => $this->FirstName, 'Surname' => $this->Surname))->first()) {
            $result->error('First and Surname must be unique for each member.');
        }
    
        return $result;
    }
    

    或者为了更强大的突破:

    public function validate() {
        $result = parent::validate();
    
        if($member = Member::get()->filter(array('FirstName' => $this->FirstName, 'Surname' => $this->Surname))->first()) {
            if($member->FirstName == $this->FirstName){
                $result->error('Your Surname is fine, please change your First Name.');
            }
            if($member->Surname == $this->Surname){
                $result->error('Your First Name is fine, please change your Surname.');
            }
        }
    
        return $result;
    }
    

    【讨论】:

    • 这是一种验证字段的好方法,但我认为 Silverstripe 唯一索引变得毫无用处。
    • @muskie9 - 这不应该是验证错误并特别提及该字段....以便错误出现在该字段旁边吗?
    • @Barry 是的,可以执行其他逻辑来确定确切的字段,但这将是确保没有其他记录共享名字/姓氏值的最低要求。
    • 如何确定确切的字段并使错误出现在该字段旁边?
    【解决方案2】:

    请注意,我将 Customer 从 Member 扩展为 FirstName,Surname 来自

    我想知道 SilverStripe 是否试图在不存在的字段 Customer.FirstNameCustomer.Surname 上设置索引。也许可以尝试通过在 实际上 的表前面添加索引来限定列,如下所示:

    private static $indexes = array(
        'IndexFirstSurName' => array(
            'type' => 'unique', 
            'value' => '"Member"."FirstName","Member"."Surname"'
        )
    );
    

    您也可以考虑装饰 Member 而不是子类化它。这样您就不需要以这种方式限定查询片段。

    【讨论】:

      【解决方案3】:

      在 SilverStripe 上扩展 Member 的方法是扩展 DataExtension。正如 theruss 所说,您正在尝试在表 Customer 上创建唯一索引,而您可能没有字段 FirstNameSurname
      试试这个

      class Customer extends DataExtension
      {
          private static $indexes = array(
              'IndexFirstSurName' => array(
                  'type' => 'unique', 
                  'value' => '"FirstName","Surname"'
              )
          );
      }
      

      然后在config.yml 中让 SilverStripe 知道您的扩展程序

      Member:
        extensions:
          - Customer
      

      现在运行/dev/build?flush,您应该会看到您的索引正在创建中。

      查看here 了解有关扩展的更多信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-12
        • 1970-01-01
        • 1970-01-01
        • 2011-05-28
        相关资源
        最近更新 更多