要在 CodeIgniter 4 透過 Model 將資料寫入(insert)資料庫,要先在 Model 的地方設定好要能修改的欄位,像這樣:

protected $allowedFields=['name',  'email'];

 

之後準備一個關聯式陣列把資料帶進去:

$userModel = model(UserModel::class);
$data = [
  'name' =>$name,
  'email'=>$email
];
$userModel->insert($data);

一般我們應該都會在 Model 設定 primary_key 以及 auto increment

protected $primaryKey = 'id';

protected $useAutoIncrement = true;

 

這樣在寫入資料後,我們也可以透過 Model 取得新資料的 id

$id=$userModel->getInsertID();