Cakephp 从 table 中检索行数据

Cakephp retrieving row data from a table

我试图在单击按钮后将一个 table 中的一行数据插入到另一个中。我有一个包含 class 信息的 table。当用户点击注册时,我需要获取那个 class 的 id 并将其插入我的时间 table table.

到目前为止,我正在尝试从 POST 数据中获取 ID。但是,当我 运行 调试器时,数组中 class 的 id 为空。

我的注册函数:

public function register(){

        $classestimetable = $this->Classestimetable->newEntity();
        if ($this->request->is('post')) {

            $classestimetable->user_id = $this->Auth->user('id');
            $classestimetable->unit_id = $this->request->getData(['id']);
            debug($classestimetable);exit;
            if ($this->Classestimetable->save($classestimetable)) {
                $this->Flash->success(__('The class has been added to your schedule.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The class could not be added. Please, try again.'));
        }

}

Table代码:

<tbody>
     <?php foreach ($units as $unit): ?>
         <tr>
                <td hidden><?= h($unit->id) ?></td>
                <td><?= h($unit->className) ?></td>
                <td><?= h($unit->user->firstName), ' ', h($unit->user->lastName) ?></td>
                <td><?= h($unit->classDate) ?></td>
                <td><?= h($unit->classTime) ?></td>
                <td class="actions"> 
                    <?= $this->Form->postLink(__('Register'), ['action' => 'register', $unit->id], ['confirm' => __('Are you sure you want to register for "{0}"?', $unit->className)]) ?>
                </td>
         </tr>
     <?php endforeach; ?>
</tbody>

调试输出:

object(App\Model\Entity\Classestimetable) {

    'user_id' => (int) 11,
    'unit_id' => null,
    '[new]' => true,
    '[accessible]' => [
        'unit_id' => true,
        'user_id' => true,
        'unit' => true,
        'user' => true
    ],
    '[dirty]' => [
        'user_id' => true,
        'unit_id' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[hasErrors]' => false,
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Classestimetable'

}

工作时,我希望 unit_id 字段包含用户选择注册的 class 的 ID。

您正在使用 $this->request->getData(['id']) 获取 ID。但是在您正在构建的 URL 中,您还没有命名该参数。要么更改为:

['action' => 'register', 'id' => $unit->id]

或者将函数的定义更改为:

public function register($id)

然后使用$classestimetable->unit_id = $id;