skip to Main Content

I am having difficulty getting the blood type description to be displayed in my patients table due to receiving the blood type foreign key in Codeigniter 4.

The error happen in <td><?php echo $p['bt']['description']; ?></td> showing
ErrorException Undefined array key "bt"

  • PacientModel.php
class PacientModel extends Model
{
    ...
    public function bt()
    {
        return $this->belongsTo(BloodTypeModel::class, 'blood_type_id');
    }
}
    
  • BloodTypeModel.php
class BloodTypeModel extends Model
{
    ...
    public function blood_type()
    {
        return $this->hasMany(PacientModel::class, 'blood_type_id');
    }
} 
  • PacientController.php
    public function index()
    {
        $model = new PacientModel();
        $blood_type = new BloodTypeModel();

        $blood_types = $blood_type->findAll();
        $blood_types = array_column($blood_types, null, 'id');

        $pacients = [
            'pacients' => $model->paginate(10),
            'pager' => $model->pager,
            'blood_types' => $blood_types, 
        ];
        return view('pacient/index', $pacients);
    }
  • index.php
  <?php foreach($pacients as $p): ?>
   <tr> 
     <td><?php echo $p['bt']['description']; ?> </td>
   </tr>
  <?php endforeach; ?>

2

Answers


  1. <?php foreach ($pacients['pacients'] as $p): ?>
    <tr>
        <td><?php echo $p->bt->description; ?></td>
    </tr>
    

    Additionally, you might want to eager load the blood type relationship to avoid the N+1 query problem. In your controller, you can modify the query like this

    $pacients = [
        'pacients' => $model->with('bt')->paginate(10),
        'pager' => $model->pager,
    ];
    

    This will load the blood type relationship for all the patients in a single query.

    Login or Signup to reply.
  2. The issue is CodeIgniter 4 does not support eager loading out of the box, you need to manually join the tables or map the relationships in your controller before passing the data to the view. PacientController.php >>

    public function index()
    {
        $model = new PacientModel();
        $pacients = $model->select('pacients.*, blood_types.description as bt_description')
                          ->join('blood_types', 'pacients.blood_type_id = blood_types.id', 'left')
                          ->paginate(10);
    
        $data = [
            'pacients' => $pacients,
            'pager' => $model->pager
        ];
    
        return view('pacient/index', $data);
    }
    

    index.php

    <?php foreach($pacients as $p): ?>
    <tr> 
      <td><?php echo $p['bt_description']; ?> </td>
    </tr>
    <?php endforeach; ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search