FleaPHP 的表資料入口類 (Flea_Db_Table 子類) 提供 find($conditions, $sort, $fields)、findAll($conditions, $sort, $fields, $limit, $offset) 等方法。$conditions 參數支援**整數、字串、陣列**三種型別,靈活表達從主鍵查詢到複雜 WHERE 條件。本文系統整理所有寫法並附實戰範例。
// 假設主鍵為 id $user = $tableUsers->find(123); // 等同 WHERE `id` = 123
若主鍵非 id,需在 Model 設定 protected $_primary = 'user_id';。
$conditions = 'id < 3 AND status = "active"'; $users = $tableUsers->find($conditions); // 直接拼接到 WHERE 後,支援任意複雜 SQL 片段 // 風險:需自行防注入,建議僅用於靜態條件
$conditions = ['username' => 'dualface', 'status' => 'active']; // WHERE `username` = 'dualface' AND `status` = 'active'
$conditions = ['id = 1', 'status = "active"']; // WHERE id = 1 AND status = "active"
$conditions = [
'id < 10', // 字串片段
'sex' => 'male', // 鍵值對
'status' => 'active'
];
// WHERE id < 10 AND `sex` = 'male' AND `status` = 'active'
規則:多條件之間自動以 AND 連接。
FleaPHP 以 'in()' 為特殊鍵名支援 IN 子句。
$conditions = ['in()' => [1, 2, 3]]; // WHERE `id` IN (1, 2, 3)
$conditions = ['in()' => ['username' => ['user1', 'user2', 'user3']]];
// WHERE `username` IN ('user1', 'user2', 'user3')
// 排序:字串 'created_at DESC' 或 'name ASC, id DESC' $users = $tableUsers->find($conditions, 'created_at DESC'); // 欄位選取:字串或陣列,建議陣列 (自動加反引號) $fields = ['id', 'username', 'email']; // 或字串 'id, username, email' $users = $tableUsers->find($conditions, null, $fields);
class UserTable extends Flea_Db_Table {
protected $_name = 'user';
protected $_primary = 'id';
}
// 查詢:狀態啟用、最近登入、前 20 筆、僅需 id/name/email
$table = new UserTable();
$conditions = [
'status' => 'active',
'last_login >' => date('Y-m-d', strtotime('-30 days')), // 支援運算子後綴
'in()' => ['role_id' => [1,2]] // 角色為管理員或編輯
];
$sort = 'last_login DESC';
$fields = ['id', 'username', 'email', 'role_id'];
$users = $table->findAll($conditions, $sort, $fields, 20, 0);
| 誤區 | 正確做法 |
|---|---|
| 字串條件直接拼接變數 | 改用關聯陣列自動參數化,或手動 quoteInto() |
| IN 條件用字串拼接 | 使用 ['in()' => [$vals]] 特殊語法 |
| 主鍵非 id 卻用整數查詢 | Model 設定 $_primary 或改用陣列 ['user_id'=>123] |
| 排序欄位用戶可控未驗證 | 白名單驗證 in_array($sort, $allowedSorts) |
| 查詢所有欄位影響效能 | 指定 $fields 僅選需要欄位 |
FleaPHP $conditions 以**整數主鍵、字串片段、關聯/索引/混合陣列、in() 特殊鍵**四大模式,涵蓋 95% 查詢場景。掌握**自動 AND 連接、反引號保護、參數化防注入、IN 語法、排序欄位白名單**,即能寫出安全高效的查詢代碼。遷移至 Laravel Eloquent、Doctrine QueryBuilder 時,where/whereIn/orderBy/select 對應關係清晰,核心思想不變。