本文整理了 Yii 2 開發中高頻使用的配置、模型、查詢、分頁、資料庫操作等核心語法,適合作為開發時的快速參考卡片。
// 表前綴設置
'tablePrefix' => 'tbl_',
namespace app\models;
use yii\db\ActiveRecord;
class Article extends ActiveRecord {
public static function tableName() {
return '{{%article}}'; // 自動套用 tablePrefix
}
}
use yii\data\Pagination;
$query = Article::find()->where(['status' => 1]);
$pages = new Pagination(['totalCount' => $query->count(), 'pageSize' => 20]);
$articles = $query->offset($pages->offset)
->limit($pages->limit)
->all();
| 方法 | 說明 | 返回類型 |
|---|---|---|
all() | 查詢所有結果 | ActiveRecord[] |
one() | 查詢單條記錄 | ActiveRecord|null |
count() | 統計數量 | int |
average('col') | 平均值 | float |
min('col') / max('col') | 最小/最大值 | mixed |
scalar() | 第一行第一列的值 | mixed |
column() | 所有結果第一列組成的數組 | array |
each(100) | 批量迭代,防止內存溢出 | Generator |
// 新增
Yii::$app->db->createCommand()
->insert('article', ['title' => '標題', 'content' => '內容'])
->execute();
// 修改
Yii::$app->db->createCommand()
->update('article', ['status' => 1], 'id = 1')
->execute();
// 刪除
Yii::$app->db->createCommand()
->delete('article', 'id = 1')
->execute();
ActiveRecord::find()->select(['id', 'title']) 只查詢所需欄位,減少內存佔用。hasMany()、hasOne() 定義關係,配合 with() 預載入避免 N+1 問題。Yii::$app->db->transaction(function() { ... }) 自動提交/回滾。