使用Cakephp Restful WS,其主键与默认的'id'不同

时间:2015-11-15 14:38:23

标签: web-services cakephp routing

我想在cakephp中创建一个Web服务,但主键不是id_supp,而是采用默认值id

这是模式:

<?php
App::uses('AppModel', 'Model');
class Supplier extends AppModel {

    var $primaryKey = 'id_supp';

这是路线

Router::mapResources(array('suppliers'));

这是视图操作

public function view($id) {
        $supplier = $this->Supplier->findById($id);
        $this->set(array(
            'supplier' => $supplier,
            '_serialize' => array('supplier')
        ));
    }

通过GET访问以下网址时的结果

/suppliers/54f4dc83-0bd0-4fdd-ab8b-0a08ba3b5702.json

是:

{
"code": 500,
"url": "\/TN\/Back_rest\/suppliers\/54f4dc83-0bd0-4fdd-ab8b-0a08ba3b5702.json",
"name": "SQLSTATE[42S22]: Column not found: 1054 Unknown column &#039;Supplier.id&#039; in &#039;where clause&#039;",
"error": {
    "errorInfo": [
        "42S22",
        1054,
        "Unknown column 'Supplier.id' in 'where clause'"
    ],
    "queryString": "SELECT `Supplier`.`id_supp`, `Supplier`.`company_name`, `Supplier`.`contact_name`, `Supplier`.`contact_title`, `Supplier`.`address`, `Supplier`.`postcode`, `Supplier`.`phone`, `Supplier`.`fax`, `Supplier`.`www`, `Supplier`.`active`, `Supplier`.`created`, `Supplier`.`modified` FROM `tn`.`suppliers` AS `Supplier`   WHERE `Supplier`.`id` = '54f4dc83-0bd0-4fdd-ab8b-0a08ba3b5702'    LIMIT 1"
}}

1 个答案:

答案 0 :(得分:1)

因为cakephp使用约定优于配置,您应该使用id作为您的表主ID字段。在你的例子中,你可以找到你想要的东西:

public function view($id = null) {
    $supplier = $this->Supplier->find('first', array(
        'conditions' => array(
            'Supplier.id_supp' => $id
        )
    ));
    $this->set(array(
        'supplier' => $supplier,
        '_serialize' => array('supplier')
    ));
}

或者像这样:

public function view($id = null) {
    $this->Supplier->primaryKey = $id;
    $supplier = $this->Supplier->find('first');
    $this->set(array(
        'supplier' => $supplier,
        '_serialize' => array('supplier')
    ));
}

或者像这样:

public function view($id = null) {
    $supplier = $this->Supplier->findByIdSupp($id);
    $this->set(array(
        'supplier' => $supplier,
        '_serialize' => array('supplier')
    ));
}

选择最让你高兴的东西。