Define models with $allowedFields, $useTimestamps, $useSoftDeletes, and validation rules.
Models in CI4
namespace AppModels;
use CodeIgniterModel;
class PostModel extends Model {
protected $table = "posts";
protected $primaryKey = "id";
protected $useAutoIncrement = true;
protected $allowedFields = ["title", "body", "user_id", "slug"];
protected $useTimestamps = true;
protected $useSoftDeletes = true;
// Validation rules
protected $validationRules = [
"title" => "required|max_length[255]",
"body" => "required",
];
// Return type
protected $returnType = "AppEntitiesPost"; // or "array"
// Callbacks
protected $beforeInsert = ["hashSlug"];
protected function hashSlug(array $data): array {
if (isset($data["data"]["title"])) {
$data["data"]["slug"] = url_title($data["data"]["title"], "-", true);
}
return $data;
}
}
// Usage
$model = model(PostModel::class);
$posts = $model->findAll();
$post = $model->find(1);
$posts = $model->where("user_id", 1)->orderBy("created_at", "DESC")->findAll();