迭代php for循环以包含父ID

时间:2017-08-08 02:21:10

标签: php loops foreach yii2

我有一个存储设备的表,以及一个存储审计期间捕获的数据的表。我是用Yii2编写这个审计系统的。

以下是我的控制器和视图的片段。

控制器:

public function actionAudit()
{
    $devices = Device::find()->all();
    $deviceAudits = [new DeviceAudit()];

    for ($i = 1; $i < count($devices); $i++) {
        $deviceAudits[] = new DeviceAudit;
        // Now, how to assign
        // foreach $deviceAudit->$device->id
        // (I am guessing an array_push here?)

    }
    ....
}

查看:

...
<?php foreach ($deviceAudits as $index => $deviceAudit): ?>
<?= $form->field($deviceAudit, "[$index]device_id")->textInput() ?>
<?= $form->field($deviceAudit, "[$index]status_id")->textInput() ?>
<?= $form->field($deviceAudit, "[$index]notes")->textInput() ?>
<?php endforeach ?>
...

我已设法检索审核次数,但我不确定如何为每次检查添加外键&#34;设备ID&#34 ;.

enter image description here

1 个答案:

答案 0 :(得分:0)

通过将我的控制器修改为以下内容轻松修复,这里是:

public function actionAudit()
{
    $devices = Device::find()->all();

    foreach ($devices as $device) {
        $deviceAudit = new DeviceAudit;
        $deviceAudit->device_id = $device->id;
        $deviceAudits[] = $deviceAudit;
    }

    ....
}