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
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
This will load the blood type relationship for all the patients in a single query.
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 >>index.php