cakephp从一行中的父表中获取多个值

时间:2014-11-02 09:37:20

标签: cakephp cakephp-2.3

我有这些表

1 - 产品类别 2 - 产品 3 - 产品型号

4 - 引用项目

现在每行报价项都有这些值

id,product_category,product_id,product_model_id,support_product_id,support_prouct_model_id

现在您可以看到Quote Item中有两个产品和产品型号的实例。我需要在屏幕上显示产品名称和产品型号名称。

当我尝试在控制器中检索数据时,它只从产品和产品模型中带来一个值,而我需要每个产品和产品模型的两个实例。

以下是我尝试检索数据的方法。

$quote_items = $this->QuoteItem->find('all', array(
 'fields' => array(
                    'product_category_id',
                    'product_id',
                    'product_model_id',
                    'support_product_id, Product.name',
                    'support_product_model_id',
                    'quantity',
                    'length',
                    'unit_price',
                    'total_price',
                    'ProductCategory.name',
                    'ProductModel.name'

                ),
                'conditions' => array(
                    'quote_id' => $this->data['Quote']['quote_id']

                ),
                'contain' => array('Product', 'ProductModel', 'ProductCategory')
            ));

这就是我所看到的。您可以注意到它只获得第一个产品的产品名称和产品型号的产品名称。

array (size=4)
      'QuoteItem' => 
        array (size=9)
          'product_category_id' => string '3' (length=1)
          'product_id' => string '30' (length=2)
          'product_model_id' => string '79' (length=2)
          'support_product_id' => string '28' (length=2)
          'support_product_model_id' => string '73' (length=2)
          'quantity' => string '33' (length=2)
          'length' => string '1' (length=1)
          'unit_price' => string '456' (length=3)
          'total_price' => string '15198' (length=5)
      'Product' => 
        array (size=2)
          'name' => string 'p3' (length=2)
          'id' => string '30' (length=2)
      'ProductCategory' => 
        array (size=2)
          'name' => string 'Iron' (length=4)
          'id' => string '3' (length=1)
      'ProductModel' => 
        array (size=2)
          'name' => string 'm1' (length=2)
          'id' => string '79' (length=2)

1 个答案:

答案 0 :(得分:0)

这是您获得的数据的正确形式。可能在你的协会中你的模型QuoteItem

belongsTo = array(
    'Product' => array(..), 
    'ProductCategory', array(...),
    'ProductModel' => array(...),
);

所以添加以下关联

belongsTo = array(
    'Product' => array(..), 
    'SupportProduct', array(
        'className' => 'SupportProduct',
        'foreignKey' => 'support_product_id',
     ),
    'ProductCategory', array(...),
    'ProductModel' => array(...),
    'SupportProductModel' => array(
        'className' => 'ProductModel',
        'foreignKey' => 'support_product_model_id',
     ),
);

因此,您可以与具有不同关联名称的同一个类具有多个关联。

相关问题