CodeIgniter 4的列表中未定义数组键

ltskdhd1  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(117)

由于在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; ?>

kokeuurv

kokeuurv1#

问题是CodeIgniter 4不支持即时加载,在将数据传递到视图之前,您需要手动连接表或Map控制器中的关系。

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; ?>

uhry853o

uhry853o2#

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

字符串
另外,您可能希望立即加载血型关系,以避免N+1查询问题。

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


这将在单个查询中加载所有患者的血型关系。

相关问题