在 CakePHP 中编辑 MySQL DB table 中没有主键的数据

Edit data in the MySQL DB table with no Primary Key in CakePHP

Windows 系统上使用 cakephp-2.6.3

我只需要编辑我在 ABCData/index.php 文件中列出的 MySQL 数据库 table 中的行数据。

控制器

    public function index() {
        $this->set('abcdata', $this->ABCData->find('all'));
    }

    public function edit($custom_id = null) {
        if (!$custom_id) {
            throw new NotFoundException(__('Invalid entry'));
        }

        $post = $this->ABCData->findById($custom_id);
        if (!$abcdata) {
            throw new NotFoundException(__('Invalid entry'));
        }

        if ($this->request->is(array('post', 'put'))) {
            $this->ABCData->custom_id = $custom_id;
            if ($this->ABCData->save($this->request->data)) {
                $this->Session->setFlash(__('Your ABCData has been updated.'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(__('Unable to update your ABCData.'));
        }

        if (!$this->request->data) {
            $this->request->data = $abcdata;
        }
    }
}

型号

class ABCData extends AppModel {
    public $primaryKey = 'custom_id';
}

index.ctp

    <h3>ABCData list</h3>
<table>
    <tr>
        <th></th>
        <th>field_1</th>
        <th>field_2</th>
        <th>field_3</th>
        <th>...</th>
        <th>...</th>
        ...
    </tr>

    <?php foreach ($abcdata as $abc): ?>
    <tr>
        <td><?php echo $this->Html->link('Edit', array('action' => 'edit', $abc['ABCData']['custom_id']));?></td>
        <td><?php echo $abc['ABCData']['field_1']; ?></td>
        <td><?php echo $abc['ABCData']['field_2']; ?></td>
        <td><?php echo $abc['ABCData']['field_3']; ?></td>
        <td>...</td>
        <td>...</td>
        ...
    </tr>
    <?php endforeach; ?>
    <?php unset($abcdata); ?>
</table>

edit.ctp

<h1>Edit ABCata</h1>
<?php
    echo $this->Form->create('ABCata');
    echo $this->Form->input('title');
    echo $this->Form->input('body', array('rows' => '16'));
    echo $this->Form->input('custom_id', array('type' => 'hidden'));
    echo $this->Form->end('Save ABCata');
?>

我只有一个 table 和一个 foreign key 字段。

此处custom_id仅为唯一字段。

我得到这个错误:

Database Error

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ABCData.id' in 'where clause' ... ...

请帮忙。

正如评论中所说,如果您的模型中没有id,则无法通过id进行搜索。你可以

$post = $this->ABCData->findByCustomId($custom_id);

根据Cake约定,或者你可以指定条件如

$post = $this->ABCData->find('first', array('conditions' =>
                                           array('ABCData.custom_id' => $custom_id)));