萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Yii Framework 查詢結果轉陣列方法總覽

ActiveRecord 單筆結果轉陣列

// 單筆查詢
$post = Post::model()->find($condition, $params);
$post = Post::model()->findByPk($id, $condition, $params);
$post = Post::model()->findByAttributes($attributes, $condition, $params);

// 關鍵:attributes 屬性回傳陣列
$array = $post->attributes; // 或 $post->getAttributes()

多筆結果轉陣列

方法一:foreach 迴圈

findAllByAttributes($attributes);
$result = [];
foreach ($models as $model) {
    $result[] = $model->attributes;
}

方法二:array_map (PHP 5.3+ 匿名函數)

attributes;
}, Post::model()->findAllByAttributes($attributes));

方法三:asArray() 查詢建構器 (Yii 1.1.14+ / Yii 2)

findAllByAttributes($attributes, ['asArray' => true]);

// Yii 2 Query Builder
$rows = (new \yii\db\Query())
    ->from('post')
    ->where($attributes)
    ->asArray()
    ->all();

效能與記憶體考量

  • asArray() 直接回傳陣列,跳過 ActiveRecord 物件建構,**效能最佳、記憶體最省**
  • 大量資料 (千筆以上) **強烈建議用 asArray() 或 Query Builder**
  • 需使用 AR 方法/關聯/驗證時才實體化物件

常見陷阱

  • findAll() 回傳空陣列而非 null,直接 foreach 安全
  • attributes 包含所有表欄位,含關聯欄位需用 getAttributes(['field1', 'field2']) 過濾
  • 關聯資料 (with()) 不在 attributes 中,需 getRelatedRecords() 或手動合併
copyright © 萬盛學電腦網 all rights reserved