yii框架學習(二)

  1. 模型
    1. orderby的使用:
      ->orderBy(['addtime'=>SORT_DESC, 'sort'=>SORT_ASC])->all()
    2. 在使用find()查詢的時候, 指定查詢字段:
      find()->select('id, title, content') 指定查詢的字段
    3. 塊賦值, 使用attributes, 好比 $psychological->attributes = $input; 把數組一次性賦值給attributes 屬性, 可是要注意, 要確保模型類中的rules方法, 已經包含了要賦值的字段不然attributes 屬性接收不到值. 就不能保存成功
    4. where 做爲查詢條件單獨拿出來的時候, 想使用  <  >  >=  <=  <>  進行範圍查詢的時候, 要怎麼寫?
      $where = [
            'and',
            ['<', 'minscore', $score],
            ['>', 'maxscore', $score],
       ];
      //查詢知足minscore<$score而且maxscore>$score 的記錄
    5. yii2中同時鏈接兩個或以上數據庫:(若是在本地開發完,傳到線上服務器, 須要把配置的數據庫的用戶名和密碼改爲線上數據庫的
      )
      1. 在config目錄下web.php文件中的components數組裏配置
        'db2' => [
                    'class' => 'yii\db\Connection',
                    'dsn' => 'mysql:host=localhost;dbname=quickapp',
                    'username' => 'root',
                    'password' => 'root',
                    'charset' => 'utf8',
                ],
      2. 在繼承ActiveRecord的模型中設置表名,rules等,必需要注意一點, yii默認鏈接的是components裏面的db設置的數據庫, 因此當鏈接其餘數據庫的時候, 就必需要重寫 getDb() 方法, 很簡單php

        public static function getDb()
            {
                return \Yii::$app->db2; //db2就是components裏的db2下標
            }

        OK, 能夠使用了.前端

    6.  yii打印SQL語句:
      echo RecycleModel::find()
                  ->alias('r')
                  ->select('r.name as rubbish, c.id, c.name, c.code, c.inc, c.des,c.req')
                  ->leftJoin(['c'=>RecycleCateModel::tableName()], 'r.category_id=c.id')
                  ->where($where)
                  ->orderBy(['modified'=>SORT_DESC])
                  ->limit('10')
                  ->asArray()->createCommand()->getRawSql();exit;

       

    7. 添加數據()mysql

      $usercode = \Yii::$app->db->createCommand()
                  ->batchInsert(UserVoucher::tableName(), ['code', 'cat_id','userId', 'gettime', 'expire'], [
                  [$code['code'], $id, $userId, time(), $code['expire']],
                 ])->execute();      //  \Yii::$app->db  這裏的db, 若是換成db2, 就是往db2數據庫裏插入數據. 

       

    8. 連表查詢分頁
      $count = VoucherCode::find()
      ->alias('v')
      ->leftJoin(['c'=>RubbishCate::tableName()], 'v.cat_id=c.id and v.is_delete=0')
      ->where($where)
      ->count(); //查詢符合連表數據總數
      $p = new Pagination(['totalCount'=>$count, 'pageSize'=>15]);
      $code = VoucherCode::find()
      ->alias('v')
      ->leftJoin(['c'=>RubbishCate::tableName()], 'v.cat_id=c.id and v.is_delete=0')
      ->select('v.*, c.name')
      ->where($where)
      ->offset($p->offset)
      ->limit($p->limit)
      ->asArray()
      ->all(); //查詢數據
      return $this->render('/rubbish-voucher/list', ['code'=>$code, 'pagination'=>$p]);
      //views視圖調用
      <?php echo \yii\widgets\LinkPager::widget([
      'pagination' => $pagination,
      'prevPageLabel' => '上一頁',
      'nextPageLabel' => '下一頁',
      'firstPageLabel' => '首頁',
      'lastPageLabel' => '尾頁',
      'maxButtonCount' => 5,
      'options' => [
      'class' => 'pagination',
      ],
      'prevPageCssClass' => 'page-item',
      'pageCssClass' => "page-item",
      'nextPageCssClass' => 'page-item',
      'firstPageCssClass' => 'page-item',
      'lastPageCssClass' => 'page-item',
      'linkOptions' => [
      'class' => 'page-link',
      ],
      'disabledListItemSubTagOptions' => ['tag' => 'a', 'class' => 'page-link'],
      ])
      ?>

       

    9.  

      條件查詢:
      $status = \Yii::$app->request->get('status', '');   //獲取用戶傳入的條件
      $where = [];
      if($status != ''){         
           $where['status'] = $status;       
      }
      $where['is_delete'] = 0;

       

    10.  

      多對多關聯
      //課程表和用戶表多對多關聯, 課程course模型裏獲取用戶表字段, 中間表爲 user_course, 中間表寫在viaTable()裏
      public
      function getUser() { return $this->hasMany(User::className(), ['id'=>'uid'])->viaTable('user_course', ['course_id'=>'id']); } //或者使用via() //獲取關聯表的屬性 $user = Course::findOne($v['id'])->user; //統計有多少人 $num = count(Course::findOne($v['id'])->user);

       

    11.  

       接口返回分頁數據
      $count = Course::find()->where($where)->count();  //數據總數
      $p = new Pagination(['totalCount'=>$count, 'pageSize'=>$pagesize]);  //實例化分頁類
      $course = Course::find()->select('id, title, pic_url, sections, teacher, fee, free')->where($where)->offset(($page-1)*$pagesize)->limit($p->limit)->all();   //前端傳入第幾頁$page和每頁顯示多少條$pagesize, 主要是offset方法裏的參數怎麼寫

       或者這麼寫web

      $course = Course::find()->select('id, title, pic_url, sections, teacher, fee, free')->where($where)->offset(($page-1)*$pagesize)->limit($pagesize)->all();

       

    12.  

      $model->errors; 打印數據驗證過程當中的錯誤信息 
    13. 根據where條件查詢指定字段, 拼接field時候, 若是有重複字段仍然能夠正常查詢的. 而且若是沒有指定where條件, 默認查詢幾個字段
      if(isset($refund_rate))
                  $where['refund_rate'] = $refund_rate;
              if(isset($row_sate_rate))
                  $where['row_sate_rate'] = $row_sate_rate;
              if(isset($film_playnum))
                  $where['film_playnum'] = $film_playnum;
              if(isset($layout_ratio))
                  $where['layout_ratio'] = $layout_ratio;
              if(isset($person_time))
                  $where['person_time'] = $person_time;
      if(isset($date))
      $where['date'] = $date;
      //設置查詢的指定字段 $field = ''; if(isset($where)){ $field = implode(',', array_keys($where)); } $field .= ', id, movie_name, split_box_total, synthesize_total, date '; //多加date 並不會報錯 $result = TicketMovie::find()->select($field)->where($where)->offset(($page-1)*$pagesize)->limit($pagesize)->asArray()->all();
相關文章
相關標籤/搜索