多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# README ## 控制器 \basic\controllers\SiteController.php ``` <?php namespace app\controllers; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use yii\filters\VerbFilter; use app\models\LoginForm; use app\models\ContactForm; class SiteController extends Controller { public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['logout'], 'rules' => [ [ 'actions' => ['logout'], 'allow' => true, 'roles' => ['@'], ], ], ], 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'logout' => ['post'], ], ], ]; } public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], ]; } public function actionIndex() { return $this->render('index'); } public function actionLogin() { if (!\Yii::$app->user->isGuest) { return $this->goHome(); } $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } return $this->render('login', [ 'model' => $model, ]); } public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } public function actionContact() { $model = new ContactForm(); if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) { Yii::$app->session->setFlash('contactFormSubmitted'); return $this->refresh(); } return $this->render('contact', [ 'model' => $model, ]); } public function actionAbout() { return $this->render('about'); } } ``` \basic\controllers\IndexController.php ``` <?php namespace app\controllers; use app\controllers\CommonController; class IndexController extends CommonController { public function actionIndex() { $this->layout = "layout1"; return $this->render("index"); } } ``` \basic\controllers\CommonController.php ``` <?php namespace app\controllers; use yii\web\Controller; use app\models\Category; use app\models\Cart; use app\models\User; use app\models\Product; use Yii; class CommonController extends Controller { public function init() { $menu = Category::getMenu(); $this->view->params['menu'] = $menu; $data = []; $data['products'] = []; $total = 0; if (Yii::$app->session['isLogin']) { $userid = User::find()->where('username = :name', [":name" => Yii::$app->session['loginname']])->one()->userid; if (!empty($userid)) { $carts = Cart::find()->where('userid = :uid', [':uid' => $userid])->asArray()->all(); foreach($carts as $k=>$pro) { $product = Product::find()->where('productid = :pid', [':pid' => $pro['productid']])->one(); $data['products'][$k]['cover'] = $product->cover; $data['products'][$k]['title'] = $product->title; $data['products'][$k]['productnum'] = $pro['productnum']; $data['products'][$k]['price'] = $pro['price']; $data['products'][$k]['productid'] = $pro['productid']; $data['products'][$k]['cartid'] = $pro['cartid']; $total += $data['products'][$k]['price'] * $data['products'][$k]['productnum']; } } } $data['total'] = $total; $this->view->params['cart'] = $data; } } ``` \basic\controllers\ProductController.php ``` <?php namespace app\controllers; use app\controllers\CommonController; use Yii; use app\models\Product; use yii\data\Pagination; class ProductController extends CommonController { public function actionIndex() { $this->layout = "layout2"; $cid = Yii::$app->request->get("cateid"); $where = "cateid = :cid and ison = '1'"; $params = [':cid' => $cid]; $model = Product::find()->where($where, $params); $all = $model->asArray()->all(); $count = $model->count(); $pageSize = Yii::$app->params['pageSize']['frontproduct']; $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]); $all = $model->offset($pager->offset)->limit($pager->limit)->asArray()->all(); $tui = $model->Where($where . ' and istui = \'1\'', $params)->orderby('createtime desc')->limit(5)->asArray()->all(); $hot = $model->Where($where . ' and ishot = \'1\'', $params)->orderby('createtime desc')->limit(5)->asArray()->all(); $sale = $model->Where($where . ' and issale = \'1\'', $params)->orderby('createtime desc')->limit(5)->asArray()->all(); return $this->render("index", ['sale' => $sale, 'tui' => $tui, 'hot' => $hot, 'all' => $all, 'pager' => $pager, 'count' => $count]); } public function actionDetail() { $this->layout = "layout2"; $productid = Yii::$app->request->get("productid"); $product = Product::find()->where('productid = :id', [':id' => $productid])->asArray()->one(); return $this->render("detail", ['product' => $product]); } } ``` \basic\controllers\MemberController.php ``` <?php namespace app\controllers; use app\controllers\CommonController; use app\models\User; use Yii; class MemberController extends CommonController { public function actionAuth() { $this->layout = 'layout2'; $model = new User; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->login($post)) { return $this->goBack(Yii::$app->request->referrer); } } return $this->render("auth", ['model' => $model]); } public function actionLogout() { Yii::$app->session->remove('loginname'); Yii::$app->session->remove('isLogin'); if (!isset(Yii::$app->session['isLogin'])) { return $this->goBack(Yii::$app->request->referrer); } } public function actionReg() { $model = new User; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->regByMail($post)) { Yii::$app->session->setFlash('info', '电子邮件发送成功'); } } $this->layout = 'layout2'; return $this->render('auth', ['model' => $model]); } public function actionQqlogin() { require_once("../vendor/qqlogin/qqConnectAPI.php"); $qc = new \QC(); $qc->qq_login(); } public function actionQqcallback() { require_once("../vendor/qqlogin/qqConnectAPI.php"); $auth = new \OAuth(); $accessToken = $auth->qq_callback(); $openid = $auth->get_openid(); $qc = new \QC($accessToken, $openid); $userinfo = $qc->get_user_info(); $session = Yii::$app->session; $session['userinfo'] = $userinfo; $session['openid'] = $openid; if (User::find()->where('openid = :openid', [':openid' => $openid])->one()) { $session['loginname'] = $userinfo['nickname']; $session['isLogin'] = 1; return $this->redirect(['index/index']); } return $this->redirect(['member/qqreg']); } public function actionQqreg() { $this->layout = "layout2"; $model = new User; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $session = Yii::$app->session; $post['User']['openid'] = $session['openid']; if ($model->reg($post, 'qqreg')) { $session['loginname'] = $session['userinfo']['nickname']; $session['isLogin'] = 1; return $this->redirect(['index/index']); } } return $this->render('qqreg', ['model' => $model]); } } ``` \basic\controllers\AddressController.php ``` <?php namespace app\controllers; use app\controllers\CommonController; use Yii; use app\models\User; use app\models\Address; class AddressController extends CommonController { public function actionAdd() { if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } $loginname = Yii::$app->session['loginname']; $userid = User::find()->where('username = :name or useremail = :email', [':name' => $loginname, ':email' => $loginname])->one()->userid; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $post['userid'] = $userid; $post['address'] = $post['address1'].$post['address2']; $data['Address'] = $post; $model = new Address; $model->load($data); $model->save(); } return $this->redirect($_SERVER['HTTP_REFERER']); } public function actionDel() { if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } $loginname = Yii::$app->session['loginname']; $userid = User::find()->where('username = :name or useremail = :email', [':name' => $loginname, ':email' => $loginname])->one()->userid; $addressid = Yii::$app->request->get('addressid'); if (!Address::find()->where('userid = :uid and addressid = :aid', [':uid' => $userid, ':aid' => $addressid])->one()) { return $this->redirect($_SERVER['HTTP_REFERER']); } Address::deleteAll('addressid = :aid', [':aid' => $addressid]); return $this->redirect($_SERVER['HTTP_REFERER']); } } ``` \basic\controllers\CartController.php ``` <?php namespace app\controllers; use app\controllers\CommonController; use app\models\User; use app\models\Cart; use app\models\Product; use Yii; class CartController extends CommonController { public function actionIndex() { if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } $userid = User::find()->where('username = :name', [':name' => Yii::$app->session['loginname']])->one()->userid; $cart = Cart::find()->where('userid = :uid', [':uid' => $userid])->asArray()->all(); $data = []; foreach ($cart as $k=>$pro) { $product = Product::find()->where('productid = :pid', [':pid' => $pro['productid']])->one(); $data[$k]['cover'] = $product->cover; $data[$k]['title'] = $product->title; $data[$k]['productnum'] = $pro['productnum']; $data[$k]['price'] = $pro['price']; $data[$k]['productid'] = $pro['productid']; $data[$k]['cartid'] = $pro['cartid']; } $this->layout = 'layout1'; return $this->render("index", ['data' => $data]); } public function actionAdd() { if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } $userid = User::find()->where('username = :name', [':name' => Yii::$app->session['loginname']])->one()->userid; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $num = Yii::$app->request->post()['productnum']; $data['Cart'] = $post; $data['Cart']['userid'] = $userid; } if (Yii::$app->request->isGet) { $productid = Yii::$app->request->get("productid"); $model = Product::find()->where('productid = :pid', [':pid' => $productid])->one(); $price = $model->issale ? $model->saleprice : $model->price; $num = 1; $data['Cart'] = ['productid' => $productid, 'productnum' => $num, 'price' => $price, 'userid' => $userid]; } if (!$model = Cart::find()->where('productid = :pid and userid = :uid', [':pid' => $data['Cart']['productid'], ':uid' => $data['Cart']['userid']])->one()) { $model = new Cart; } else { $data['Cart']['productnum'] = $model->productnum + $num; } $data['Cart']['createtime'] = time(); $model->load($data); $model->save(); return $this->redirect(['cart/index']); } public function actionMod() { $cartid = Yii::$app->request->get("cartid"); $productnum = Yii::$app->request->get("productnum"); Cart::updateAll(['productnum' => $productnum], 'cartid = :cid', [':cid' => $cartid]); } public function actionDel() { $cartid = Yii::$app->request->get("cartid"); Cart::deleteAll('cartid = :cid', [':cid' => $cartid]); return $this->redirect(['cart/index']); } } ``` \basic\controllers\OrderController.php ``` <?php namespace app\controllers; use app\controllers\CommonController; use Yii; use app\models\Order; use app\models\OrderDetail; use app\models\Cart; use app\models\Product; use app\models\User; use app\models\Address; use app\models\Pay; use dzer\express\Express; class OrderController extends CommonController { public function actionIndex() { $this->layout = "layout2"; if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } $loginname = Yii::$app->session['loginname']; $userid = User::find()->where('username = :name or useremail = :email', [':name' => $loginname, ':email' => $loginname])->one()->userid; $orders = Order::getProducts($userid); return $this->render("index", ['orders' => $orders]); } public function actionCheck() { if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } $orderid = Yii::$app->request->get('orderid'); $status = Order::find()->where('orderid = :oid', [':oid' => $orderid])->one()->status; if ($status != Order::CREATEORDER && $status != Order::CHECKORDER) { return $this->redirect(['order/index']); } $loginname = Yii::$app->session['loginname']; $userid = User::find()->where('username = :name or useremail = :email', [':name' => $loginname, ':email' => $loginname])->one()->userid; $addresses = Address::find()->where('userid = :uid', [':uid' => $userid])->asArray()->all(); $details = OrderDetail::find()->where('orderid = :oid', [':oid' => $orderid])->asArray()->all(); $data = []; foreach($details as $detail) { $model = Product::find()->where('productid = :pid' , [':pid' => $detail['productid']])->one(); $detail['title'] = $model->title; $detail['cover'] = $model->cover; $data[] = $detail; } $express = Yii::$app->params['express']; $expressPrice = Yii::$app->params['expressPrice']; $this->layout = "layout1"; return $this->render("check", ['express' => $express, 'expressPrice' => $expressPrice, 'addresses' => $addresses, 'products' => $data]); } public function actionAdd() { if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } $transaction = Yii::$app->db->beginTransaction(); try { if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $ordermodel = new Order; $ordermodel->scenario = 'add'; $usermodel = User::find()->where('username = :name or useremail = :email', [':name' => Yii::$app->session['loginname'], ':email' => Yii::$app->session['loginname']])->one(); if (!$usermodel) { throw new \Exception(); } $userid = $usermodel->userid; $ordermodel->userid = $userid; $ordermodel->status = Order::CREATEORDER; $ordermodel->createtime = time(); if (!$ordermodel->save()) { throw new \Exception(); } $orderid = $ordermodel->getPrimaryKey(); foreach ($post['OrderDetail'] as $product) { $model = new OrderDetail; $product['orderid'] = $orderid; $product['createtime'] = time(); $data['OrderDetail'] = $product; if (!$model->add($data)) { throw new \Exception(); } Cart::deleteAll('productid = :pid' , [':pid' => $product['productid']]); Product::updateAllCounters(['num' => -$product['productnum']], 'productid = :pid', [':pid' => $product['productid']]); } } $transaction->commit(); }catch(\Exception $e) { $transaction->rollback(); return $this->redirect(['cart/index']); } return $this->redirect(['order/check', 'orderid' => $orderid]); } public function actionConfirm() { //addressid, expressid, status, amount(orderid,userid) try { if (Yii::$app->session['isLogin'] != 1) { return $this->redirect(['member/auth']); } if (!Yii::$app->request->isPost) { throw new \Exception(); } $post = Yii::$app->request->post(); $loginname = Yii::$app->session['loginname']; $usermodel = User::find()->where('username = :name or useremail = :email', [':name' => $loginname, ':email' => $loginname])->one(); if (empty($usermodel)) { throw new \Exception(); } $userid = $usermodel->userid; $model = Order::find()->where('orderid = :oid and userid = :uid', [':oid' => $post['orderid'], ':uid' => $userid])->one(); if (empty($model)) { throw new \Exception(); } $model->scenario = "update"; $post['status'] = Order::CHECKORDER; $details = OrderDetail::find()->where('orderid = :oid', [':oid' => $post['orderid']])->all(); $amount = 0; foreach($details as $detail) { $amount += $detail->productnum*$detail->price; } if ($amount <= 0) { throw new \Exception(); } $express = Yii::$app->params['expressPrice'][$post['expressid']]; if ($express < 0) { throw new \Exception(); } $amount += $express; $post['amount'] = $amount; $data['Order'] = $post; if ($model->load($data) && $model->save()) { return $this->redirect(['order/pay', 'orderid' => $post['orderid'], 'paymethod' => $post['paymethod']]); } }catch(\Exception $e) { return $this->redirect(['index/index']); } } public function actionPay() { try{ if (Yii::$app->session['isLogin'] != 1) { throw new \Exception(); } $orderid = Yii::$app->request->get('orderid'); $paymethod = Yii::$app->request->get('paymethod'); if (empty($orderid) || empty($paymethod)) { throw new \Exception(); } if ($paymethod == 'alipay') { return Pay::alipay($orderid); } }catch(\Exception $e) {} return $this->redirect(['order/index']); } public function actionGetexpress() { $expressno = Yii::$app->request->get('expressno'); $res = Express::search($expressno); echo $res; exit; } public function actionReceived() { $orderid = Yii::$app->request->get('orderid'); $order = Order::find()->where('orderid = :oid', [':oid' => $orderid])->one(); if (!empty($order) && $order->status == Order::SENDED) { $order->status = Order::RECEIVED; $order->save(); } return $this->redirect(['order/index']); } } ``` \basic\controllers\PayController.php ``` <?php namespace app\controllers; use app\controllers\CommonController; use app\models\Pay; use Yii; class PayController extends CommonController { public $enableCsrfValidation = false; public function actionNotify() { if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if (Pay::notify($post)) { echo "success"; exit; } echo "fail"; exit; } } public function actionReturn() { $this->layout = 'layout1'; $status = Yii::$app->request->get('trade_status'); if ($status == 'TRADE_SUCCESS') { $s = 'ok'; } else { $s = 'no'; } return $this->render("status", ['status' => $s]); } } ``` ## 模型 \basic\models\Category.php ``` <?php namespace app\models; use yii\db\ActiveRecord; use Yii; use yii\helpers\ArrayHelper; class Category extends ActiveRecord { public static function tableName() { return "{{%category}}"; } public function attributeLabels() { return [ 'parentid' => '上级分类', 'title' => '分类名称' ]; } public function rules() { return [ ['parentid', 'required', 'message' => '上级分类不能为空'], ['title', 'required', 'message' => '标题名称不能为空'], ['createtime', 'safe'] ]; } public function add($data) { $data['Category']['createtime'] = time(); if ($this->load($data) && $this->save()) { return true; } return false; } public function getData() { $cates = self::find()->all(); $cates = ArrayHelper::toArray($cates); return $cates; } public function getTree($cates, $pid = 0) { $tree = []; foreach($cates as $cate) { if ($cate['parentid'] == $pid) { $tree[] = $cate; $tree = array_merge($tree, $this->getTree($cates, $cate['cateid'])); } } return $tree; } public function setPrefix($data, $p = "|-----") { $tree = []; $num = 1; $prefix = [0 => 1]; while($val = current($data)) { $key = key($data); if ($key > 0) { if ($data[$key - 1]['parentid'] != $val['parentid']) { $num ++; } } if (array_key_exists($val['parentid'], $prefix)) { $num = $prefix[$val['parentid']]; } $val['title'] = str_repeat($p, $num).$val['title']; $prefix[$val['parentid']] = $num; $tree[] = $val; next($data); } return $tree; } public function getOptions() { $data = $this->getData(); $tree = $this->getTree($data); $tree = $this->setPrefix($tree); $options = ['添加顶级分类']; foreach($tree as $cate) { $options[$cate['cateid']] = $cate['title']; } return $options; } public function getTreeList() { $data = $this->getData(); $tree = $this->getTree($data); return $tree = $this->setPrefix($tree); } public static function getMenu() { $top = self::find()->where('parentid = :pid', [":pid" => 0])->asArray()->all(); $data = []; foreach((array)$top as $k=>$cate) { $cate['children'] = self::find()->where("parentid = :pid", [":pid" => $cate['cateid']])->asArray()->all(); $data[$k] = $cate; } return $data; } } ``` \basic\models\Address.php ``` <?php namespace app\models; use yii\db\ActiveRecord; use Yii; class Address extends ActiveRecord { public static function tableName() { return "{{%address}}"; } public function rules() { return [ [['userid', 'firstname', 'lastname', 'address', 'email', 'telephone'], 'required'], [['createtime', 'postcode'],'safe'], ]; } } ``` \basic\models\Cart.php ``` <?php namespace app\models; use yii\db\ActiveRecord; use Yii; class Cart extends ActiveRecord { public static function tableName() { return "{{%cart}}"; } public function rules() { return [ [['productid','productnum','userid','price'], 'required'], ['createtime', 'safe'] ]; } } ``` \basic\models\ContactForm.php ``` <?php namespace app\models; use Yii; use yii\base\Model; /** * ContactForm is the model behind the contact form. */ class ContactForm extends Model { public $name; public $email; public $subject; public $body; public $verifyCode; /** * @return array the validation rules. */ public function rules() { return [ // name, email, subject and body are required [['name', 'email', 'subject', 'body'], 'required'], // email has to be a valid email address ['email', 'email'], // verifyCode needs to be entered correctly ['verifyCode', 'captcha'], ]; } /** * @return array customized attribute labels */ public function attributeLabels() { return [ 'verifyCode' => 'Verification Code', ]; } /** * Sends an email to the specified email address using the information collected by this model. * @param string $email the target email address * @return boolean whether the model passes validation */ public function contact($email) { if ($this->validate()) { Yii::$app->mailer->compose() ->setTo($email) ->setFrom([$this->email => $this->name]) ->setSubject($this->subject) ->setTextBody($this->body) ->send(); return true; } return false; } } ``` \basic\models\LoginForm.php ``` <?php namespace app\models; use Yii; use yii\base\Model; /** * LoginForm is the model behind the login form. */ class LoginForm extends Model { public $username; public $password; public $rememberMe = true; private $_user = false; /** * @return array the validation rules. */ public function rules() { return [ // username and password are both required [['username', 'password'], 'required'], // rememberMe must be a boolean value ['rememberMe', 'boolean'], // password is validated by validatePassword() ['password', 'validatePassword'], ]; } /** * Validates the password. * This method serves as the inline validation for password. * * @param string $attribute the attribute currently being validated * @param array $params the additional name-value pairs given in the rule */ public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, 'Incorrect username or password.'); } } } /** * Logs in a user using the provided username and password. * @return boolean whether the user is logged in successfully */ public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } return false; } /** * Finds user by [[username]] * * @return User|null */ public function getUser() { if ($this->_user === false) { $this->_user = User::findByUsername($this->username); } return $this->_user; } } ``` \basic\models\Order.php ``` <?php namespace app\models; use yii\db\ActiveRecord; use app\models\OrderDetail; use app\models\Product; use app\models\Category; class Order extends ActiveRecord { const CREATEORDER = 0; const CHECKORDER = 100; const PAYFAILED = 201; const PAYSUCCESS = 202; const SENDED = 220; const RECEIVED = 260; public static $status = [ self::CREATEORDER => '订单初始化', self::CHECKORDER => '待支付', self::PAYFAILED => '支付失败', self::PAYSUCCESS => '等待发货', self::SENDED => '已发货', self::RECEIVED => '订单完成', ]; public $products; public $zhstatus; public $username; public $address; public function rules() { return [ [['userid', 'status'], 'required', 'on' => ['add']], [['addressid', 'expressid', 'amount', 'status'], 'required', 'on' => ['update']], ['expressno', 'required', 'message' => '请输入快递单号', 'on' => 'send'], ['createtime', 'safe', 'on' => ['add']], ]; } public static function tableName() { return "{{%order}}"; } public function attributeLabels() { return [ 'expressno' => '快递单号', ]; } public function getDetail($orders) { foreach($orders as $order){ $order = self::getData($order); } return $orders; } public static function getData($order) { $details = OrderDetail::find()->where('orderid = :oid', [':oid' => $order->orderid])->all(); $products = []; foreach($details as $detail) { $product = Product::find()->where('productid = :pid', [':pid' => $detail->productid])->one(); $product->num = $detail->productnum; $products[] = $product; } $order->products = $products; $order->username = User::find()->where('userid = :uid', [':uid' => $order->userid])->one()->username; $order->address = Address::find()->where('addressid = :aid', [':aid' => $order->addressid])->one(); if (empty($order->address)) { $order->address = ""; } else { $order->address = $order->address->address; } $order->zhstatus = self::$status[$order->status]; return $order; } public static function getProducts($userid) { $orders = self::find()->where('status > 0 and userid = :uid', [':uid' => $userid])->orderBy('createtime desc')->all(); foreach($orders as $order) { $details = OrderDetail::find()->where('orderid = :oid', [':oid' => $order->orderid])->all(); $products = []; foreach($details as $detail) { $product = Product::find()->where('productid = :pid', [':pid' => $detail->productid])->one(); $product->num = $detail->productnum; $product->price = $detail->price; $product->cate = Category::find()->where('cateid = :cid', [':cid' => $product->cateid])->one()->title; $products[] = $product; } $order->zhstatus = self::$status[$order->status]; $order->products = $products; } return $orders; } } ``` \basic\models\OrderDetail.php ``` <?php namespace app\models; use yii\db\ActiveRecord; class OrderDetail extends ActiveRecord { public function rules() { return [ [['productid', 'productnum', 'price', 'orderid', 'createtime'],'required'], ]; } public static function tableName() { return "{{%order_detail}}"; } public function add($data) { if ($this->load($data) && $this->save()) { return true; } return false; } } ``` \basic\models\Pay.php ``` <?php namespace app\models; use app\models\Order; use app\models\OrderDetail; use app\models\Product; class Pay{ public static function alipay($orderid) { $amount = Order::find()->where('orderid = :oid', [':oid' => $orderid])->one()->amount; if (!empty($amount)) { $alipay = new \AlipayPay(); $giftname = "慕课商城"; $data = OrderDetail::find()->where('orderid = :oid', [':oid' => $orderid])->all(); $body = ""; foreach($data as $pro) { $body .= Product::find()->where('productid = :pid', [':pid' => $pro['productid']])->one()->title . " - "; } $body .= "等商品"; $showUrl = "http://shop.mr-jason.com"; $html = $alipay->requestPay($orderid, $giftname, $amount, $body, $showUrl); echo $html; } } public static function notify($data) { $alipay = new \AlipayPay(); $verify_result = $alipay->verifyNotify(); if ($verify_result) { $out_trade_no = $data['extra_common_param']; $trade_no = $data['trade_no']; $trade_status = $data['trade_status']; $status = Order::PAYFAILED; if ($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') { $status = Order::PAYSUCCESS; $order_info = Order::find()->where('orderid = :oid', [':oid' => $out_trade_no])->one(); if (!$order_info) { return false; } if ($order_info->status == Order::CHECKORDER) { Order::updateAll(['status' => $status, 'tradeno' => $trade_no, 'tradeext' => json_encode($data)], 'orderid = :oid', [':oid' => $order_info->orderid]); } else { return false; } } return true; } else { return false; } } } ``` \basic\models\Product.php ``` <?php namespace app\models; use yii\db\ActiveRecord; class Product extends ActiveRecord { const AK = 'toix9okVaTB0uz6oxPe_vTnW-psg62jGuQOb01uZ'; const SK = '9BbqEK8nmW-LlLWnmt4Aqe3CWWKN-IiSJMDlY0a3'; const DOMAIN = 'o7zgluxwg.bkt.clouddn.com'; const BUCKET = 'imooc-shop'; public $cate; public function rules() { return [ ['title', 'required', 'message' => '标题不能为空'], ['descr', 'required', 'message' => '描述不能为空'], ['cateid', 'required', 'message' => '分类不能为空'], ['price', 'required', 'message' => '单价不能为空'], [['price','saleprice'], 'number', 'min' => 0.01, 'message' => '价格必须是数字'], ['num', 'integer', 'min' => 0, 'message' => '库存必须是数字'], [['issale','ishot', 'pics', 'istui'],'safe'], [['cover'], 'required'], ]; } public function attributeLabels() { return [ 'cateid' => '分类名称', 'title' => '商品名称', 'descr' => '商品描述', 'price' => '商品价格', 'ishot' => '是否热卖', 'issale' => '是否促销', 'saleprice' => '促销价格', 'num' => '库存', 'cover' => '图片封面', 'pics' => '商品图片', 'ison' => '是否上架', 'istui' => '是否推荐', ]; } public static function tableName() { return "{{%product}}"; } public function add($data) { if ($this->load($data) && $this->save()) { return true; } return false; } } ``` \basic\models\Profile.php ``` <?php namespace app\models; use yii\db\ActiveRecord; class Profile extends ActiveRecord { public static function tableName() { return "{{%profile}}"; } } ``` \basic\models\User.php ``` <?php namespace app\models; use yii\db\ActiveRecord; use Yii; class User extends ActiveRecord { public $repass; public $loginname; public $rememberMe = true; public static function tableName() { return "{{%user}}"; } public function rules() { return [ ['loginname', 'required', 'message' => '登录用户名不能为空', 'on' => ['login']], ['openid', 'required', 'message' => 'openid不能为空', 'on' => ['reg', 'regbymail', 'qqreg']], ['username', 'required', 'message' => '用户名不能为空', 'on' => ['reg', 'regbymail', 'qqreg']], ['openid', 'unique', 'message' => 'openid已经被注册', 'on' => ['reg', 'regbymail', 'qqreg']], ['username', 'unique', 'message' => '用户已经被注册', 'on' => ['reg', 'regbymail', 'qqreg']], ['useremail', 'required', 'message' => '电子邮件不能为空', 'on' => ['reg', 'regbymail']], ['useremail', 'email', 'message' => '电子邮件格式不正确', 'on' => ['reg', 'regbymail']], ['useremail', 'unique', 'message' => '电子邮件已被注册', 'on' => ['reg', 'regbymail']], ['userpass', 'required', 'message' => '用户密码不能为空', 'on' => ['reg', 'login', 'regbymail', 'qqreg']], ['repass', 'required', 'message' => '确认密码不能为空', 'on' => ['reg', 'qqreg']], ['repass', 'compare', 'compareAttribute' => 'userpass', 'message' => '两次密码输入不一致', 'on' => ['reg', 'qqreg']], ['userpass', 'validatePass', 'on' => ['login']], ]; } public function validatePass() { if (!$this->hasErrors()) { $loginname = "username"; if (preg_match('/@/', $this->loginname)) { $loginname = "useremail"; } $data = self::find()->where($loginname.' = :loginname and userpass = :pass', [':loginname' => $this->loginname, ':pass' => md5($this->userpass)])->one(); if (is_null($data)) { $this->addError("userpass", "用户名或者密码错误"); } } } public function attributeLabels() { return [ 'username' => '用户名', 'userpass' => '用户密码', 'repass' => '确认密码', 'useremail' => '电子邮箱', 'loginname' => '用户名/电子邮箱', ]; } public function reg($data, $scenario = 'reg') { $this->scenario = $scenario; if ($this->load($data) && $this->validate()) { $this->createtime = time(); $this->userpass = md5($this->userpass); if ($this->save(false)) { return true; } return false; } return false; } public function getProfile() { return $this->hasOne(Profile::className(), ['userid' => 'userid']); } public function login($data) { $this->scenario = "login"; if ($this->load($data) && $this->validate()) { //做点有意义的事 $lifetime = $this->rememberMe ? 24*3600 : 0; $session = Yii::$app->session; session_set_cookie_params($lifetime); $session['loginname'] = $this->loginname; $session['isLogin'] = 1; return (bool)$session['isLogin']; } return false; } public function regByMail($data) { $data['User']['username'] = 'imooc_'.uniqid(); $data['User']['userpass'] = uniqid(); $this->scenario = 'regbymail'; if ($this->load($data) && $this->validate()) { $mailer = Yii::$app->mailer->compose('createuser', ['userpass' => $data['User']['userpass'], 'username' => $data['User']['username']]); $mailer->setFrom('imooc_shop@163.com'); $mailer->setTo($data['User']['useremail']); $mailer->setSubject('慕课商城-新建用户'); if ($mailer->send() && $this->reg($data, 'regbymail')) { return true; } } return false; } } ``` # 后台 ## 后台控制器 /basic/modules/controllers/CategoryController.php ``` <?php namespace app\modules\controllers; use app\models\Category; use yii\web\Controller; use app\modules\controllers\CommonController; use Yii; class CategoryController extends CommonController { public function actionList() { $this->layout = "layout1"; $model = new Category; $cates = $model->getTreeList(); return $this->render("cates", ['cates' => $cates]); } public function actionAdd() { $model = new Category(); $list = $model->getOptions(); $this->layout = "layout1"; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->add($post)) { Yii::$app->session->setFlash("info", "添加成功"); } } return $this->render("add", ['list' => $list, 'model' => $model]); } public function actionMod() { $this->layout = "layout1"; $cateid = Yii::$app->request->get("cateid"); $model = Category::find()->where('cateid = :id', [':id' => $cateid])->one(); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->load($post) && $model->save()) { Yii::$app->session->setFlash('info', '修改成功'); } } $list = $model->getOptions(); return $this->render('add', ['model' => $model, 'list' => $list]); } public function actionDel() { try { $cateid = Yii::$app->request->get('cateid'); if (empty($cateid)) { throw new \Exception('参数错误'); } $data = Category::find()->where('parentid = :pid', [":pid" => $cateid])->one(); if ($data) { throw new \Exception('该分类下有子类,不允许删除'); } if (!Category::deleteAll('cateid = :id', [":id" => $cateid])) { throw new \Exception('删除失败'); } } catch(\Exception $e) { Yii::$app->session->setFlash('info', $e->getMessage()); } return $this->redirect(['category/list']); } } ``` /basic/modules/controllers/CommonController.php ``` <?php namespace app\modules\controllers; use yii\web\Controller; use Yii; class CommonController extends Controller { public function init() { if (Yii::$app->session['admin']['isLogin'] != 1) { return $this->redirect(['/admin/public/login']); } } } ``` /basic/modules/controllers/DefaultController.php ``` <?php namespace app\modules\controllers; use yii\web\Controller; use app\modules\controllers\CommonController; class DefaultController extends CommonController { public function actionIndex() { $this->layout = "layout1"; return $this->render('index'); } } ``` /basic/modules/controllers/ManageController.php ``` <?php namespace app\modules\controllers; use yii\web\Controller; use Yii; use app\modules\models\Admin; use yii\data\Pagination; use app\modules\controllers\CommonController; class ManageController extends CommonController { public function actionMailchangepass() { $this->layout = false; $time = Yii::$app->request->get("timestamp"); $adminuser = Yii::$app->request->get("adminuser"); $token = Yii::$app->request->get("token"); $model = new Admin; $myToken = $model->createToken($adminuser, $time); if ($token != $myToken) { $this->redirect(['public/login']); Yii::$app->end(); } if (time() - $time > 300) { $this->redirect(['public/login']); Yii::$app->end(); } if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->changePass($post)) { Yii::$app->session->setFlash('info', '密码修改成功'); } } $model->adminuser = $adminuser; return $this->render("mailchangepass", ['model' => $model]); } public function actionManagers() { $this->layout = "layout1"; $model = Admin::find(); $count = $model->count(); $pageSize = Yii::$app->params['pageSize']['manage']; $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]); $managers = $model->offset($pager->offset)->limit($pager->limit)->all(); return $this->render("managers", ['managers' => $managers, 'pager' => $pager]); } public function actionReg() { $this->layout = 'layout1'; $model = new Admin; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->reg($post)) { Yii::$app->session->setFlash('info', '添加成功'); } else { Yii::$app->session->setFlash('info', '添加失败'); } } $model->adminpass = ''; $model->repass = ''; return $this->render('reg', ['model' => $model]); } public function actionDel() { $adminid = (int)Yii::$app->request->get("adminid"); if (empty($adminid)) { $this->redirect(['manage/managers']); } $model = new Admin; if ($model->deleteAll('adminid = :id', [':id' => $adminid])) { Yii::$app->session->setFlash('info', '删除成功'); $this->redirect(['manage/managers']); } } public function actionChangeemail() { $this->layout = 'layout1'; $model = Admin::find()->where('adminuser = :user', [':user' => Yii::$app->session['admin']['adminuser']])->one(); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->changeemail($post)) { Yii::$app->session->setFlash('info', '修改成功'); } } $model->adminpass = ""; return $this->render('changeemail', ['model' => $model]); } public function actionChangepass() { $this->layout = "layout1"; $model = Admin::find()->where('adminuser = :user', [':user' => Yii::$app->session['admin']['adminuser']])->one(); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->changepass($post)) { Yii::$app->session->setFlash('info', '修改成功'); } } $model->adminpass = ''; $model->repass = ''; return $this->render('changepass', ['model' => $model]); } } ``` /basic/modules/controllers/OrderController.php ``` <?php namespace app\modules\controllers; use app\models\Order; use app\models\OrderDetail; use app\models\Product; use app\models\User; use app\models\Address; use yii\web\Controller; use yii\data\Pagination; use Yii; use app\modules\controllers\CommonController; class OrderController extends CommonController { public function actionList() { $this->layout = "layout1"; $model = Order::find(); $count = $model->count(); $pageSize = Yii::$app->params['pageSize']['order']; $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]); $data = $model->offset($pager->offset)->limit($pager->limit)->all(); $data = Order::getDetail($data); return $this->render('list', ['pager' => $pager, 'orders' => $data]); } public function actionDetail() { $this->layout = "layout1"; $orderid = (int)Yii::$app->request->get('orderid'); $order = Order::find()->where('orderid = :oid', [':oid' => $orderid])->one(); $data = Order::getData($order); return $this->render('detail', ['order' => $data]); } public function actionSend() { $this->layout = "layout1"; $orderid = (int)Yii::$app->request->get('orderid'); $model = Order::find()->where('orderid = :oid', [':oid' => $orderid])->one(); $model->scenario = "send"; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $model->status = Order::SENDED; if ($model->load($post) && $model->save()) { Yii::$app->session->setFlash('info', '发货成功'); } } return $this->render('send', ['model' => $model]); } } ``` /basic/modules/controllers/ProductController.php ``` <?php namespace app\modules\controllers; use app\models\Category; use app\models\Product; use yii\web\Controller; use Yii; use yii\data\Pagination; use crazyfd\qiniu\Qiniu; use app\modules\controllers\CommonController; class ProductController extends CommonController { public function actionList() { $model = Product::find(); $count = $model->count(); $pageSize = Yii::$app->params['pageSize']['product']; $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]); $products = $model->offset($pager->offset)->limit($pager->limit)->all(); $this->layout = "layout1"; return $this->render("products", ['pager' => $pager, 'products' => $products]); } public function actionAdd() { $this->layout = "layout1"; $model = new Product; $cate = new Category; $list = $cate->getOptions(); unset($list[0]); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $pics = $this->upload(); if (!$pics) { $model->addError('cover', '封面不能为空'); } else { $post['Product']['cover'] = $pics['cover']; $post['Product']['pics'] = $pics['pics']; } if ($pics && $model->add($post)) { Yii::$app->session->setFlash('info', '添加成功'); } else { Yii::$app->session->setFlash('info', '添加失败'); } } return $this->render("add", ['opts' => $list, 'model' => $model]); } private function upload() { if ($_FILES['Product']['error']['cover'] > 0) { return false; } $qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET); $key = uniqid(); $qiniu->uploadFile($_FILES['Product']['tmp_name']['cover'], $key); $cover = $qiniu->getLink($key); $pics = []; foreach ($_FILES['Product']['tmp_name']['pics'] as $k => $file) { if ($_FILES['Product']['error']['pics'][$k] > 0) { continue; } $key = uniqid(); $qiniu->uploadFile($file, $key); $pics[$key] = $qiniu->getLink($key); } return ['cover' => $cover, 'pics' => json_encode($pics)]; } public function actionMod() { $this->layout = "layout1"; $cate = new Category; $list = $cate->getOptions(); unset($list[0]); $productid = Yii::$app->request->get("productid"); $model = Product::find()->where('productid = :id', [':id' => $productid])->one(); if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); $qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET); $post['Product']['cover'] = $model->cover; if ($_FILES['Product']['error']['cover'] == 0) { $key = uniqid(); $qiniu->uploadFile($_FILES['Product']['tmp_name']['cover'], $key); $post['Product']['cover'] = $qiniu->getLink($key); $qiniu->delete(basename($model->cover)); } $pics = []; foreach($_FILES['Product']['tmp_name']['pics'] as $k => $file) { if ($_FILES['Product']['error']['pics'][$k] > 0) { continue; } $key = uniqid(); $qiniu->uploadfile($file, $key); $pics[$key] = $qiniu->getlink($key); } $post['Product']['pics'] = json_encode(array_merge((array)json_decode($model->pics, true), $pics)); if ($model->load($post) && $model->save()) { Yii::$app->session->setFlash('info', '修改成功'); } } return $this->render('add', ['model' => $model, 'opts' => $list]); } public function actionRemovepic() { $key = Yii::$app->request->get("key"); $productid = Yii::$app->request->get("productid"); $model = Product::find()->where('productid = :pid', [':pid' => $productid])->one(); $qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET); $qiniu->delete($key); $pics = json_decode($model->pics, true); unset($pics[$key]); Product::updateAll(['pics' => json_encode($pics)], 'productid = :pid', [':pid' => $productid]); return $this->redirect(['product/mod', 'productid' => $productid]); } public function actionDel() { $productid = Yii::$app->request->get("productid"); $model = Product::find()->where('productid = :pid', [':pid' => $productid])->one(); $key = basename($model->cover); $qiniu = new Qiniu(Product::AK, Product::SK, Product::DOMAIN, Product::BUCKET); $qiniu->delete($key); $pics = json_decode($model->pics, true); foreach($pics as $key=>$file) { $qiniu->delete($key); } Product::deleteAll('productid = :pid', [':pid' => $productid]); return $this->redirect(['product/list']); } public function actionOn() { $productid = Yii::$app->request->get("productid"); Product::updateAll(['ison' => '1'], 'productid = :pid', [':pid' => $productid]); return $this->redirect(['product/list']); } public function actionOff() { $productid = Yii::$app->request->get("productid"); Product::updateAll(['ison' => '0'], 'productid = :pid', [':pid' => $productid]); return $this->redirect(['product/list']); } } ``` /basic/modules/controllers/PublicController.php ``` <?php namespace app\modules\controllers; use yii\web\Controller; use app\modules\models\Admin; use Yii; class PublicController extends Controller { public function actionLogin() { $this->layout = false; $model = new Admin; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->login($post)) { $this->redirect(['default/index']); Yii::$app->end(); } } return $this->render("login", ['model' => $model]); } public function actionLogout() { Yii::$app->session->removeAll(); if (!isset(Yii::$app->session['admin']['isLogin'])) { $this->redirect(['public/login']); Yii::$app->end(); } $this->goback(); } public function actionSeekpassword() { $this->layout = false; $model = new Admin; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->seekPass($post)) { Yii::$app->session->setFlash('info', '电子邮件已经发送成功,请查收'); } } return $this->render("seekpassword", ['model' => $model]); } } ``` /basic/modules/controllers/UserController.php ``` <?php namespace app\modules\controllers; use yii\web\Controller; use yii\data\Pagination; use app\models\User; use app\models\Profile; use Yii; use app\modules\controllers\CommonController; class UserController extends CommonController { public function actionUsers() { $model = User::find()->joinWith('profile'); $count = $model->count(); $pageSize = Yii::$app->params['pageSize']['user']; $pager = new Pagination(['totalCount' => $count, 'pageSize' => $pageSize]); $users = $model->offset($pager->offset)->limit($pager->limit)->all(); $this->layout = "layout1"; return $this->render('users', ['users' => $users, 'pager' => $pager]); } public function actionReg() { $this->layout = "layout1"; $model = new User; if (Yii::$app->request->isPost) { $post = Yii::$app->request->post(); if ($model->reg($post)) { Yii::$app->session->setFlash('info', '添加成功'); } } $model->userpass = ''; $model->repass = ''; return $this->render("reg", ['model' => $model]); } public function actionDel() { try{ $userid = (int)Yii::$app->request->get('userid'); if (empty($userid)) { throw new \Exception(); } $trans = Yii::$app->db->beginTransaction(); if ($obj = Profile::find()->where('userid = :id', [':id' => $userid])->one()) { $res = Profile::deleteAll('userid = :id', [':id' => $userid]); if (empty($res)) { throw new \Exception(); } } if (!User::deleteAll('userid = :id', [':id' => $userid])) { throw new \Exception(); } $trans->commit(); } catch(\Exception $e) { if (Yii::$app->db->getTransaction()) { $trans->rollback(); } } $this->redirect(['user/users']); } } ``` ## 后台模型 \basic\modules\models\Admin.php ``` <?php namespace app\modules\models; use yii\db\ActiveRecord; use Yii; class Admin extends ActiveRecord { public $rememberMe = true; public $repass; public static function tableName() { return "{{%admin}}"; } public function attributeLabels() { return [ 'adminuser' => '管理员账号', 'adminemail' => '管理员邮箱', 'adminpass' => '管理员密码', 'repass' => '确认密码', ]; } public function rules() { return [ ['adminuser', 'required', 'message' => '管理员账号不能为空', 'on' => ['login', 'seekpass', 'changepass', 'adminadd', 'changeemail']], ['adminpass', 'required', 'message' => '管理员密码不能为空', 'on' => ['login', 'changepass', 'adminadd', 'changeemail']], ['rememberMe', 'boolean', 'on' => 'login'], ['adminpass', 'validatePass', 'on' => ['login', 'changeemail']], ['adminemail', 'required', 'message' => '电子邮箱不能为空', 'on' => ['seekpass', 'adminadd', 'changeemail']], ['adminemail', 'email', 'message' => '电子邮箱格式不正确', 'on' => ['seekpass', 'adminadd', 'changeemail']], ['adminemail', 'unique', 'message' => '电子邮箱已被注册', 'on' => ['adminadd', 'changeemail']], ['adminuser', 'unique', 'message' => '管理员已被注册', 'on' => 'adminadd'], ['adminemail', 'validateEmail', 'on' => 'seekpass'], ['repass', 'required', 'message' => '确认密码不能为空', 'on' => ['changepass', 'adminadd']], ['repass', 'compare', 'compareAttribute' => 'adminpass', 'message' => '两次密码输入不一致', 'on' => ['changepass', 'adminadd']], ]; } public function validatePass() { if (!$this->hasErrors()) { $data = self::find()->where('adminuser = :user and adminpass = :pass', [":user" => $this->adminuser, ":pass" => md5($this->adminpass)])->one(); if (is_null($data)) { $this->addError("adminpass", "用户名或者密码错误"); } } } public function validateEmail() { if (!$this->hasErrors()) { $data = self::find()->where('adminuser = :user and adminemail = :email', [':user' => $this->adminuser, ':email' => $this->adminemail])->one(); if (is_null($data)) { $this->addError("adminemail", "管理员电子邮箱不匹配"); } } } public function login($data) { $this->scenario = "login"; if ($this->load($data) && $this->validate()) { //做点有意义的事 $lifetime = $this->rememberMe ? 24*3600 : 0; $session = Yii::$app->session; session_set_cookie_params($lifetime); $session['admin'] = [ 'adminuser' => $this->adminuser, 'isLogin' => 1, ]; $this->updateAll(['logintime' => time(), 'loginip' => ip2long(Yii::$app->request->userIP)], 'adminuser = :user', [':user' => $this->adminuser]); return (bool)$session['admin']['isLogin']; } return false; } public function seekPass($data) { $this->scenario = "seekpass"; if ($this->load($data) && $this->validate()) { //做点有意义的事 $time = time(); $token = $this->createToken($data['Admin']['adminuser'], $time); $mailer = Yii::$app->mailer->compose('seekpass', ['adminuser' => $data['Admin']['adminuser'], 'time' => $time, 'token' => $token]); $mailer->setFrom("imooc_shop@163.com"); $mailer->setTo($data['Admin']['adminemail']); $mailer->setSubject("慕课商城-找回密码"); if ($mailer->send()) { return true; } } return false; } public function createToken($adminuser, $time) { return md5(md5($adminuser).base64_encode(Yii::$app->request->userIP).md5($time)); } public function changePass($data) { $this->scenario = "changepass"; if ($this->load($data) && $this->validate()) { return (bool)$this->updateAll(['adminpass' => md5($this->adminpass)], 'adminuser = :user', [':user' => $this->adminuser]); } return false; } public function reg($data) { $this->scenario = 'adminadd'; if ($this->load($data) && $this->validate()) { $this->adminpass = md5($this->adminpass); if ($this->save(false)) { return true; } return false; } return false; } public function changeEmail($data) { $this->scenario = "changeemail"; if ($this->load($data) && $this->validate()) { return (bool)$this->updateAll(['adminemail' => $this->adminemail], 'adminuser = :user', [':user' => $this->adminuser]); } return false; } } ``` ## 数据库 ``` DROP TABLE IF EXISTS `shop_admin`; CREATE TABLE IF NOT EXISTS `shop_admin`( `adminid` INT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `adminuser` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '管理员账号', `adminpass` CHAR(32) NOT NULL DEFAULT '' COMMENT '管理员密码', `adminemail` VARCHAR(50) NOT NULL DEFAULT '' COMMENT '管理员电子邮箱', `logintime` INT UNSIGNED NOT NULL DEFAULT '0' COMMENT '登录时间', `loginip` BIGINT NOT NULL DEFAULT '0' COMMENT '登录IP', `createtime` INT UNSIGNED NOT NULL DEFAULT '0' COMMENT '创建时间', PRIMARY KEY(`adminid`), UNIQUE shop_admin_adminuser_adminpass(`adminuser`, `adminpass`), UNIQUE shop_admin_adminuser_adminemail(`adminuser`, `adminemail`) )ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `shop_admin`(adminuser,adminpass,adminemail,createtime) VALUES('admin', md5('123'), 'shop@imooc.com', UNIX_TIMESTAMP()); DROP TABLE IF EXISTS `shop_user`; CREATE TABLE IF NOT EXISTS `shop_user`( `userid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `username` VARCHAR(32) NOT NULL DEFAULT '', `userpass` CHAR(32) NOT NULL DEFAULT '', `useremail` VARCHAR(100) NOT NULL DEFAULT '', `createtime` INT UNSIGNED NOT NULL DEFAULT '0', UNIQUE shop_user_username_userpass(`username`,`userpass`), UNIQUE shop_user_useremail_userpass(`useremail`,`userpass`), PRIMARY KEY(`userid`) )ENGINE=InnoDB DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `shop_profile`; CREATE TABLE IF NOT EXISTS `shop_profile`( `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键ID', `truename` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '真实姓名', `age` TINYINT UNSIGNED NOT NULL DEFAULT '0' COMMENT '年龄', `sex` ENUM('0','1','2') NOT NULL DEFAULT '0' COMMENT '性别', `birthday` date NOT NULL DEFAULT '2016-01-01' COMMENT '生日', `nickname` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '昵称', `company` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '公司', `userid` BIGINT UNSIGNED NOT NULL DEFAULT '0' COMMENT '用户的ID', `createtime` INT UNSIGNED NOT NULL DEFAULT '0' COMMENT '创建时间', PRIMARY KEY(`id`), UNIQUE shop_profile_userid(`userid`) )ENGINE=InnoDB DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `shop_category`; CREATE TABLE IF NOT EXISTS `shop_category`( `cateid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, `title` VARCHAR(32) NOT NULL DEFAULT '', `parentid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `createtime` INT UNSIGNED NOT NULL DEFAULT '0', PRIMARY KEY(`cateid`), KEY shop_category_parentid(`parentid`) )ENGINE=InnoDB DEFAULT CHARSET=utf8; DROP TABLE IF EXISTS `shop_product`; CREATE TABLE IF NOT EXISTS `shop_product`( `productid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `cateid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `title` VARCHAR(200) NOT NULL DEFAULT '', `descr` TEXT, `num` INT UNSIGNED NOT NULL DEFAULT '0', `price` DECIMAL(10,2) NOT NULL DEFAULT '0.00', `cover` VARCHAR(200) NOT NULL DEFAULT '', `pics` TEXT, `issale` ENUM('0','1') NOT NULL DEFAULT '0', `ishot` ENUM('0','1') NOT NULL DEFAULT '0', `istui` ENUM('0','1') NOT NULL DEFAULT '0', `saleprice` DECIMAL(10,2) NOT NULL DEFAULT '0.00', `ison` ENUM('0','1') NOT NULL DEFAULT '1', `createtime` INT UNSIGNED NOT NULL DEFAULT '0', KEY shop_product_cateid(`cateid`), KEY shop_product_ison(`ison`) )ENGINE=InnoDB DEFAULT CHARSET='utf8'; DROP TABLE IF EXISTS `shop_cart`; CREATE TABLE IF NOT EXISTS `shop_cart`( `cartid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `productid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `productnum` INT UNSIGNED NOT NULL DEFAULT '0', `price` DECIMAL(10,2) NOT NULL DEFAULT '0.00', `userid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `createtime` INT UNSIGNED NOT NULL DEFAULT '0', KEY shop_cart_productid(`productid`), KEY shop_cart_userid(`userid`) )ENGINE=InnoDB DEFAULT CHARSET='utf8'; DROP TABLE IF EXISTS `shop_order`; CREATE TABLE IF NOT EXISTS `shop_order`( `orderid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `userid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `addressid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `amount` DECIMAL(10,2) NOT NULL DEFAULT '0.00', `status` INT UNSIGNED NOT NULL DEFAULT '0', `expressid` INT UNSIGNED NOT NULL DEFAULT '0', `expressno` VARCHAR(50) NOT NULL DEFAULT '', `tradeno` VARCHAR(100) NOT NULL DEFAULT '', `tradeext` TEXT, `createtime` INT UNSIGNED NOT NULL DEFAULT '0', `updatetime` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, KEY shop_order_userid(`userid`), KEY shop_order_addressid(`addressid`), KEY shop_order_expressid(`expressid`) )ENGINE=InnoDB DEFAULT CHARSET='utf8'; DROP TABLE IF EXISTS `shop_order_detail`; CREATE TABLE IF NOT EXISTS `shop_order_detail`( `detailid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `productid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `price` DECIMAL(10,2) NOT NULL DEFAULT '0.00', `productnum` INT UNSIGNED NOT NULL DEFAULT '0', `orderid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `createtime` INT UNSIGNED NOT NULL DEFAULT '0', KEY shop_order_detail_productid(`productid`), KEY shop_order_detail_orderid(`orderid`) )ENGINE=InnoDB DEFAULT CHARSET='utf8'; DROP TABLE IF EXISTS `shop_address`; CREATE TABLE IF NOT EXISTS `shop_address`( `addressid` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `firstname` VARCHAR(32) NOT NULL DEFAULT '', `lastname` VARCHAR(32) NOT NULL DEFAULT '', `company` VARCHAR(100) NOT NULL DEFAULT '', `address` TEXT, `postcode` CHAR(6) NOT NULL DEFAULT '', `email` VARCHAR(100) NOT NULL DEFAULT '', `telephone` VARCHAR(20) NOT NULL DEFAULT '', `userid` BIGINT UNSIGNED NOT NULL DEFAULT '0', `createtime` INT UNSIGNED NOT NULL DEFAULT '0', KEY shop_address_userid(`userid`) )ENGINE=InnoDB DEFAULT CHARSET='utf8'; ```