Search code examples
phpcodeigniter-4

mysqli_sql_exception unknown column in codeigniter when using findAll()


I am learning CodeIgniter4, and i got stuck while using function findAll(), it says this: mysqli_sql_exception #1054 Unknown column 'cursos.deleted_at' in 'where clause'

<?php namespace App\Models;

use CodeIgniter\Model;

class Codigofacilito_model extends Model
{
  protected $table      = 'cursos';
  protected $primaryKey = 'idCurso';

  protected $returnType     = 'array';
  protected $useSoftDeletes = true;

  protected $allowedFields = ['nombreCurso','videosCurso'];

  protected $useTimestamps = false;
  protected $createdField  = 'created_at';
  protected $updatedField  = 'updated_at';
  protected $deletedField  = 'deleted_at';

  protected $validationRules    = [];
  protected $validationMessages = [];
  protected $skipValidation     = false;

  function __construct()
  {
    if (is_callable('parent::__construct')) {
      parent::__construct();
    }
  }

  function crearCurso($arr)
  {
    $this->insert
    (array(
        'nombreCurso' => $arr['nombre'],
        'videosCurso' => $arr['videos']
      )
    );
  }
}

Controller:

<?php namespace App\Controllers;

use App\Models\codigofacilito_model;

class Cursos extends BaseController{
  function __construct(){
    if (is_callable('parent::__construct')) {
      parent::__construct();
    }
    helper('form');
  }

  function index(){
    $modelo1=new Codigofacilito_model($db);
    $data=$modelo1->findAll();
    echo view('codigofacilito/headers');
    echo view('cursos/cursos',$data);
  }

}

The connection is correct, and all the table names and others are correct.


Solution

  • As the error says you're missing the deleted_at column in your cursos table.

    Here you told two major things to Codeigniter :

    • With protected $useSoftDeletes = true; you're telling him : I don't want to use SQL delete statement, instead update the deleted_at field
      Note that deleted_at can either be a date format (format that you can specify with $dateFormat parameter in your model) or an INTEGER.
    • With protected $deletedField = 'deleted_at';, you are setting the name of the field that will be used with soft deletes.

    Your error is catched when calling findAll() method since the framework will filter the records to those that are not soft deleted, using the field name you provided him.

    So if you want to resolve your error, either add deleted_at column in your table or change $deletedField value with your soft delete column that already exists.

    For further informations about CI4 Model configuration : https://codeigniter.com/user_guide/models/model.html#configuring-your-model

    Also since you have the $useTimestamps = false you don't need to set a name for the created_at and updated_at.