1.使用事务添加数据:
public function create() { if($this->validate()) { $trans = Yii::$app->db->beginTransaction(); $admin = new Admin(); try { $admin->setAttributes($this->getAttributes()); $admin->status = Admin::STATUS_ACTIVED; $admin->password_hash = Yii::$app->security->generatePasswordHash($this->password); $admin->created_at = time(); $admin->updated_at = time(); $admin->profile_id = $this->createProfile()->id; if($admin->save()) { $trans->commit(); return true; } $error = ''; foreach ($admin->errors as $es) { foreach ($es as $e) { $error .= ($e."<br />"); } } Yii::$app->session->setFlash('error', $error); return false; } catch (Exception $e) { Yii::$app->session->setFlash('error', $e->getMessage()); $trans->rollBack(); return false; } } else { $error = ''; foreach ($this->errors as $es) { foreach ($es as $e) { $error .= ($e."<br />"); } } Yii::$app->session->setFlash('error', $error); return false; } }
2.分类的集合管理类:
class Category { // 组合一维数组 static public function unlimitedForLevel ($cate, $parent='pid', $html = '----', $suffix = '|', $pid = null, $level = 0) { $arr = array(); foreach ($cate as $v){ if($v[$parent] == $pid){ $v['level'] = $level + 1; $v['prefix'] = str_repeat($html, $level) . ($level ? $suffix : ''); $arr[] = $v; $arr = array_merge($arr, self::unlimitedForLevel($cate, $parent, $html, $suffix, $v['id'], $level + 1)); } } return $arr; } // 组合多位数组 static public function unlimitedForLayer($cate,$name='child', $pid = 0) { $arr = array(); foreach ($cate as $v){ if($v['pid'] == $pid){ $v[$name] = self::unlimitedForLayer($cate, $name, $v['id']); $arr[] = $v; } } return $arr; } // 传递一个子分类ID返回所有的父级分类 static public function getParents($cate, $id){ $arr = array(); foreach ($cate as $v){ if($v['id'] == $id){ $arr[] = $v; $arr = array_merge(self::getParents($cate, $v['pid']), $arr); } } return $arr; } // 传递一个父级分类ID返回所有的子级分类 static public function getChilds($cate, $pid, $name='child'){ $arr = array(); foreach ($cate as $v){ if($v['pid'] == $pid){ $v[$name] = self::getChilds($cate, $v['id'], $name); $arr[] = $v; } } return $arr; } // 传递一个父级分类ID返回所有的子级ID static public function getChildsId($cate, $pid){ $arr = array(); foreach ($cate as $v) { if($v['pid'] == $pid){ $arr[] = $v['id']; $arr = array_merge($arr, self::getChildsId($cate, $v['id'])); } } return $arr; } }