Yii2 學習心得


<?php
/**
* Yii框架的數據庫查詢是基於pdo來執行的
* main-local 這種凡是帶local的是為了避免開發沖突設計的,可以在本地修改配置,但是不要提交就可以
*/

//sql查詢
Yii::$app->db->createCommand('select * from post')->queryAll();
Yii::$app->db->createCommand('select * from post')->queryOne();

//根據id查詢sql
Yii::$app->db->createCommand('select * from post where id = :id and status = :status')
->bindValue(':id',$_GET['id'])
->bindValue(':status',1)
->queryAll();


//使用ActiveRecord查詢
Post::find()->where(['id'=>1])->all();
Post::find()->where(['id'=>1])->one();

//設置查詢條件
$posts = Post::find()->where(['AND',['status'=>2],['author_id'=>1],['like','title','標題內容']])->orderby('id')->all();

findBySql();//這也是一種查詢方法

//或者

Post::findOne(1);
Post::findAll(['id'=>1,]);

//輸出id
$model = Post::findOne(1);
echo $model->id;


//curl其中save可以代替insert和update
//添加
$post = new Post();
$post->id = 1;
$post->status = 2;
$post->save();//等同於insert

//修改
$post = Post::findOne($id);
$post->status = 1;
$post->save();//等同於修改

//刪除
$post = Post::findOne($id);
$post->delete();


//DetailView用於顯示一條記錄的數據
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'title',
'content:ntext',
'tags:ntext',
'status',
'create_time:datetime',
'update_time:datetime',
'author_id',
],
]),

//。。。。。。。還可以添加屬性控制表單樣式
'template'=>'<tr><th style="width: 120px;">{label}</th><td>{value}</td></tr>',//設置label的樣式
'options'=>['class'=>'table table-striped table-bodered detail-view'],//設置整個表格的屬性樣式
?>


像上面的這種ntext、datetime這種的都是展示的格式
ntext會把網頁的標簽都展示出來
datetime展示的yii的時間形式Sep 23, 2015 4:51:54 PM

變化時間那么就用這種樣子的
[
'attribute'=>'update_time',
'value'=>date('Y-m-d H:i:s',$model->update_time),
],

 


//ListView和GirdView可以對數據進行分頁、排序和過濾
hasOne用於多對一、一對一的情況
hasMany用於一對多的情況


例如:我的model層代碼有
public function getStatus0()
{
return $this->hasOne(Poststatus::className(), ['id' => 'status']);
}

那么我在展示的時候就可以寫成:
[
'label'=>'狀態',
'value'=>$model->status0->name,
],

或者

public function getAuthor()
{
return $this->hasOne(Adminuser::className(), ['id' => 'author_id']);
}

展示也可以寫成
[
'attribute'=>'author_id',
'value'=>$model->author->nickname,
]

 

//別名-用來替代網址或者一些路徑之類的(必須用@開頭)
Yii::setAlias('@foo','/path/to/foo');//文件路徑別名
Yii::setAlias('@foo','http://www.baidu.com');//URL別名

別名的使用

$cache = new FileCache([
'cachePath'=>'@runtime/cache',
]);

 

//下拉框示例
<?= $form->field($model, 'status')
->dropDownList(['1'=>'草稿','2'=>'已發布'],['prompt'=>'請選擇狀態']);
?>

那么和數據庫交互以后的下拉框可以這樣寫
<?php
$poststatus = Poststatus::find()->all();//model也是要注意引用
$allStatus = ArrayHelper::map($poststatus,'id','name');//類文件需要引用以后才可以這樣簡寫ArrayHelper
?>
<?= $form->field($model, 'status')
->dropDownList($allStatus,
['prompt'=>'請選擇狀態']);?>

又或者這樣寫:
<?php
$psArray = Yii::$app->db->createCommand('select id,name from poststatus')->queryAll();
$allStatus = ArrayHelper::map($psArray,'id','name');
?>


又或者用query-buider
<?php
$allStatus = (new \yii\db\query())
->select(['name','id'])
->from('poststatus')
->indexBy('id')
->column();
?>


或者
<?php
$allStatus = Poststatus::find()
->select(['name','id'])
->orderBy('position')
->indexBy('id')
->column();
?>

 

 


//from查詢(支持將查詢出來的結果當成一張表再查詢)
$subQuery = (new \yii\db\Query())->select('id')->from('user')->where('status=1');
$query->from(['u'=>$subQuery]);


//limit的用法
$query->limit(10)->offset(20); 表示從第20條開始取數,取10條記錄


關於查詢的一些語法可以參考http://www.yiichina.com/doc/guide/2.0/db-query-builder

 

圖片總結:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 preg_split('/\s*,\s*/',trim($tags),-1,PREG_SPLIT_NO_EMPTY);匹配空白字符開頭或者空白字符結尾的字符串並且轉換成數組

array_values  取得數組中所有的值(而不是鍵名)
array_diff   取得的是數組的差集(也就是兩個數組相比較,其中一個數組比另一個數組多出的部分)

array_diff($new,$old)  和  array_diff($old,$new)是有差別的


上面我們說過了設置時間在id查詢單個model的時候的例子
接下來我們在說一下在 GridView::widget中時間的設置
[
    'attribute'=>'update_time',
    'format'=>['date','php:Y-m-d H:i:s'],
],






聲明一下GridView::widget的例子:
<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            //這一行就代表的是序列號
           // ['class' => 'yii\grid\SerialColumn'],

//            'id',
            ['attribute'=>'id',
             'contentOptions'=>['width'=>'30px;'],//設置單元格寬度
            ],
            'title',
            //'author_id',
            ['attribute'=>'author_id',
             'value'=>'author.nickname',
            ],
//            'content:ntext',
            'tags:ntext',
//            'status',
            ['attribute'=>'status',
             'value'=>'status0.name',
                //一下這個屬性是用來設置下拉查詢的樣式以及數據交互的查詢的
              'filter'=>\common\models\Poststatus::find()
                ->select(['name','id'])//查詢這兩個字段
                ->orderBy('position')//根據數據庫這個字段實現排序
                ->indexBy('id')//用數據庫查到的作為索引
                ->column(),//查詢列數據
            ],
            // 'create_time:datetime',
//             'update_time:datetime',
            [
                'attribute'=>'update_time',
                'format'=>['date','php:Y-m-d H:i:s'],
            ],


            ['class' => 'yii\grid\ActionColumn'],//這一行代表的是查看、修改、刪除
        ],
    ]); ?>




//文章內容太長做截取
[
    'attribute'=>'content',
    'value'=>function($model){
        $tmpStr = strip_tags($model->content);//去掉html的標簽
        $tmplength = mb_strlen($tmpStr);//計算長度
        return mb_substr($tmpStr,0,20,'utf-8').(($tmplength>20)?'...':'');//判斷長度大於20以后做拼接
    }
],

這樣截取直接在代碼中寫有時候可能太過於繁瑣不好維護,那么我們就可以封裝類

在model層做一個封裝

public function getBeginning(){
$tmpStr = strip_tags($this->content);
$tmpLen = mb_strlen($tmpStr);
return mb_substr($tmpStr,0,20,'utf-8').(($tmpLen)>20?'...':'');
}

接下來就可以在試圖層調用了

 [
'attribute'=>'content',
'value'=>'beginning',
// 'value'=>function($model){
// $tmpStr = strip_tags($model->content);//去掉html的標簽
// $tmplength = mb_strlen($tmpStr);//計算長度
// return mb_substr($tmpStr,0,20,'utf-8').(($tmplength>20)?'...':'');//判斷長度大於20以后做拼接
// }
],

 

 

圖文:

 

 

 

 

 


 

 

 

上述錯誤是字段重復導致的,檢查數據表,更換字段,同時更換規則即可!

 

或者在查詢的時候指定表名就不用這么大改了:

 

 





免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM