Php 基于if语句(Yii 1.x.x)在模型中禁用save()

Php 基于if语句(Yii 1.x.x)在模型中禁用save(),php,yii-extensions,yii,yii-components,Php,Yii Extensions,Yii,Yii Components,我正在我的模型中运行一些代码,它执行以下操作: public function beforeSave() { $this->parent_exists = FALSE; // search for existing parent.. $existing_parent = Myparents::model()->findByAttributes(array('email' => $this->email)); // if (isset($existin

我正在我的模型中运行一些代码,它执行以下操作:

public function beforeSave()
{
  $this->parent_exists = FALSE;
  // search for existing parent..
  $existing_parent = Myparents::model()->findByAttributes(array('email' => $this->email)); //

    if (isset($existing_parent) && is_object($existing_parent))
    {
      // WHERE I AM STUCK...
      // need to disable/override the save() to prevent the INSERT into the table
    } else {
      // proceed as normal with the 'normal' save() method
    }
}
如果IF语句为true,但如果该语句为FALSE,则可以使用save()正常进行,有人能解释我如何通过save()方法防止插入查询发生吗


有什么想法吗?

只需在beforeSave()中返回true或false,如下所示,如果beforeSave()返回false,则不会进行插入。还要注意,您需要像我在下面所做的那样调用父实现,以便正确引发事件

public function beforeSave()
{
  if(parent::beforeSave()){
      $this->parent_exists = FALSE;
      // search for existing parent..
      $existing_parent = Myparents::model()->findByAttributes(array('email' => $this->email)); //

       if (isset($existing_parent) && is_object($existing_parent))
       {
            // WHERE I AM STUCK...
            // need to disable/override the save() to prevent the INSERT into the table
            return false;
       } else {
            return true;
           // proceed as normal with the 'normal' save() method
       } 
      return true;// return T/F for not set case as well
    } else {
        return false;
    }
}

请参见

将此设置为验证规则,而不是保存前设置。记住,beforeSave只会在“单个项目”保存操作上触发


注意,beforeSave()不会在“批量”(多个项目)保存时触发。欢迎使用Yii。原因是单次插入和多次插入的查询方式不同。。每个ORM都有它的怪癖activeRecord也一样:)
/**
 * @return array validation rules for model attributes.
 */
public function rules()
{
    return array(
       array('email', 'hasNoParent'),
    );
}


/**
 * Check for parent
 *
 * @param string $attribute
 * @param array  $params
 */
public function hasNoParent($attribute, $params)
{
    $existingParent = Myparents::model()->findByAttributes(array(
        'email' => $this->$attribute
    ));

    if (isset($existingParent) && $existingParent instanceof Myparents){
         $this->addError($attribute, 'your password is not strong enough!');
    }
}