在CakePHP中连接多个表并检索数据

时间:2014-07-16 14:46:06

标签: php mysql database database-design cakephp-2.0

更新问题

我正在尝试加入CakePHP中的多个表并检索他们的数据。 我创建了我的模型但没有得到相关的结果。

以下是我的表结构。

Fields needed :
    Equipment Name
    Equipment Description
    Equipment Type name according to Equipment id
    Equipment Type Sizes names according to Type id
    Sizes Stock.

型号:Equipment.php

class Equipment extends AppModel {
    public $useTable = 'equipments';
    var $name = 'Equipment';
    public $cacheQueries = false;

    public $hasMany = array(
        'Sizes' => array(
            'className' => 'EquipmentSize',
            'foreignKey' => 'equipment_id'

        )
    );
}

型号:EquipmentSizes .php

class EquipmentSizes extends AppModel {
    public $useTable = 'equipment_sizes';
    var $name = 'EquipmentSizes';
    public $cacheQueries = false;
    public $belongsTo = array(
        'Equipment' => array(
            'className' => 'Equipment',
            'foreignKey' => 'equipment_id',
            'fields' => array('id', 'sizes')
        )
    );
 }

型号:EquipmentType.php

class EquipmentType extends AppModel {
    public $useTable = 'equipment_types';
    var $name = 'EquipmentType';
    public $cacheQueries = false;

    public $hasMany = array(
        'Sizes' => array(
            'className' => 'EquipmentTypesSize',
            'foreignKey' => 'equipment_type_id'
        )
    );
}

型号:EquipmentTypesSizes.php

class EquipmentTypesSizes extends AppModel {
    public $useTable = 'equipment_types_sizes';
    var $name = 'EquipmentTypesSizes';
    public $cacheQueries = false;
    public $belongsTo = array(
        'EquipmentType' => array(
            'className' => 'EquipmentType',
            'foreignKey' => 'equipment_type_id',
            'fields' => array('id', 'sizes')
        )
    );
}

1 个答案:

答案 0 :(得分:2)

您忘记了某些具有hasMoMany关系的模型(Equipment.php,EquipmentType.php)上的外键。首先纠正您的模型,然后尝试查询设备,您可以看到相关的设备模型。然后,您可以根据条件确定条件。

更新 - Equipment.php

class Equipment extends AppModel {
   public $useTable = 'equipments';
   var $name = 'Equipment';
   public $cacheQueries = false;

   public $hasMany = array(
     'Sizes' => array(
        'className' => 'EquipmentSize',
        'foreignKey' => 'equipment_id'

    ),
    'EquipmentType' => array(
        'className' => 'EquipmentType',
        'foreignKey' => 'equipment_id'

    )
 );

}

EquipmentSizes.php 是正确的。

更新 - EquipmentType.php

class EquipmentType extends AppModel {
    public $useTable = 'equipment_types';
    var $name = 'EquipmentType';
    public $cacheQueries = false;

    public $hasMany = array(
        'Sizes' => array(
            'className' => 'EquipmentTypesSize',
            'foreignKey' => 'equipment_type_id'
        )
    );

    public $belongsTo = array(
        'Equipment' => array(
            'className' => 'Equipment',
            'foreignKey' => 'equipment_id'
        )
    );
}

EquipmentTypesSizes.php 是正确的。