I'm planning to create an API for CRUD operations. Retrieving data from the database works flawlessly as usual and also returning is no issue. But when it comes to dates, I'm facing issues with the format. The dates are stored as DATETIME in the database and are automatically created at insert, but I want to deliver an unix timestamp when accessing via API. I've stripped down my code to the crucial parts:
PHP Code:
<?php
// Controllers/Config.php
namespace App\Controllers\API;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ConfigModel;
class Config extends ResourceController
{
use ResponseTrait;
public function index()
{
$model = new ConfigModel();
return $this->respond($model->getConfig());
}
}
// Models/ConfigModel.php
namespace App\Models;
use CodeIgniter\Model;
class ConfigModel extends Model
{
protected $table = 'configuration';
protected $primaryKey = 'id';
protected $allowedFields = ['name','value','is_default'];
protected function getCurrentConfig()
{
$query = $this->query('SELECT * FROM configuration WHERE id IN (SELECT MAX(id) FROM configuration GROUP BY name)');
return $query->getResult();
}
public function getConfig()
{
return $this->getCurrentConfig();
}
}
Code:
// Result
[
{
"id": "1",
"name": "ticket_number_format",
"value": "default",
"is_default": "1",
"create_timestamp": "2021-09-22 09:11:07" // need: 1632294667
},
{
"id": "3",
"name": "ticket_number_format_default_alphanumeric",
"value": "true",
"is_default": "1",
"create_timestamp": "2021-09-22 09:21:40" // need: 1632295300
},
// ...
}
I know that I could simply select each field in separate and enclose UNIX_TIMESTAMP(create_timestamp) but I'm planning to operate on tables with much more columns in the future as well. Also I may use the query builder instead of custom SQL for more basic selects. I've red about the getCustomResultObject(), but I can't figure out how to use it.