我想列出給定表中的所有列,這Schema::getColumnListing()做得很好,但是它按字母順序回傳列而不是它們創建的順序,有沒有辦法改變這個?
這是標準用戶表的示例:
表結構:
--- ------------------- -----------------
| 1 | id | bigint unsigned |
--- ------------------- -----------------
| 2 | name | varchar(255) |
--- ------------------- -----------------
| 3 | email | varchar(255) |
--- ------------------- -----------------
| 4 | email_verified_at | timestamp |
--- ------------------- -----------------
| 5 | password | varchar(255) |
--- ------------------- -----------------
| 6 | remember_token | varchar(100) |
--- ------------------- -----------------
| 7 | created_at | timestamp |
--- ------------------- -----------------
| 8 | updated_at | timestamp |
--- ------------------- -----------------
測驗代碼:
$model = new \App\Models\User;
$table = $model->getTable();
$columns = Schema::getColumnListing($table);
dd($columns);
輸出:
^ array:8 [▼
0 => "created_at"
1 => "email"
2 => "email_verified_at"
3 => "id"
4 => "name"
5 => "password"
6 => "remember_token"
7 => "updated_at"
]
期望的輸出:
^ array:8 [▼
0 => "id"
1 => "name"
2 => "email"
3 => "email_verified_at"
4 => "password"
5 => "remember_token"
6 => "created_at"
7 => "updated_at"
]
uj5u.com熱心網友回復:
您可以使用模型屬性。
$item = Model::where('id', 1)->first();
$attributes = array_keys($item->getOriginal());
// or
$attributes = array_keys($item->getAttributes());
dd($attributes);
uj5u.com熱心網友回復:
還沒有看過它的實作,但是如果它沒有按順序回傳列,為什么不嘗試原始mysql呢?
SHOW COLUMNS
FROM users;
在DB::select()查詢中使用它并獲取結果。
完整查詢:
$columns = \DB::select('SHOW COLUMNS FROM users');
如果要保持動態,請使用$columns = \DB::select('SHOW COLUMNS FROM ?', [$table]);
注意:代碼未經測驗。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/473015.html
