首页 > 解决方案 > CakePHP - 保存 HABTM 失败

问题描述

我有看起来像这样的表。基本上 WarehousePlace 里面可以有很多 ItemType 并且 ItemType 可以被很多 WarehousePlace 使用。但是当我尝试保存时,我得到一个数据库错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'WarehousePlacesItemType.item_type_id' in 'field list'

SQL Query: SELECT `WarehousePlacesItemType`.`item_type_id` FROM `modules`.`warehouse_places_item_types` AS `WarehousePlacesItemType` WHERE `WarehousePlacesItemType`.`warehouse_place_id` = '22' 

但是一切都是按照惯例完成的,调试数据也应该是这样,我看不出有什么问题。

仓库控制器

public function add() {
        $this->load();
        if ($this->request->is('post')) {
            $data = array(
                'WarehousePlace' => array(
                    'name' => $this->request->data['WarehousePlace']['name'],
                ),
                'ItemType' => array(
                    'ItemType' => $this->request->data['ItemType']['ItemType']
                )
            );
            $this->WarehousePlace->create();

            if ($this->WarehousePlace->saveAll($data, array('validate' => 'first', 'deep' => true))) {
//success
            }
            if ($this->WarehousePlace->validationErrors) {
                //validation
            } else {
                //error
            }
        }
    }

表:

warehouse_places_item_types(warehouse_places_id,item_types_id) -> no primary key since CakePHP 2,

warehouse_places(id, name),

item_types(id, name)

楷模:

物品种类

public $hasAndBelongsToMany = array(
    'WarehousePlace' => array(
        'className' => 'WarehousePlace',
        'joinTable' => 'warehouse_places_item_types',
        'foreignKey' => 'item_type_id',
        'associationForeignKey' => 'warehouse_place_id',
        'unique' => 'keepExisting',
    )
);

仓库地点

public $hasAndBelongsToMany = array(
    'ItemType' => array(
        'className' => 'ItemType',
        'joinTable' => 'warehouse_places_item_types',
        'foreignKey' => 'warehouse_place_id',
        'associationForeignKey' => 'item_type_id',
        'unique' => 'keepExisting',
    )
);

标签: phpcakephpassociationscakephp-2.x

解决方案


推荐阅读