由于在 Codeigniter 4 中接收到血型外键,我很难在患者表中显示血型描述。
错误发生在
<td><?php echo $p['bt']['description']; ?></td>
显示
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; ?>
<?php foreach ($pacients['pacients'] as $p): ?>
<tr>
<td><?php echo $p->bt->description; ?></td>
</tr>