6
 Product        Plan            ProductPlan
 id |name       id |name        id  | product_id | plan_id     
 1    aplha      1   a          1        1          2             
 2    bravo      2   b
 3    charlie 

我想根据 ProductPlan 查找产品名称和计划名称,如果 ProductPlan 中存在产品的产品 ID 和计划 ID,那么将显示计划和产品的名称,我尝试了很多,关系 b/w 表是正确的,但我没有t得到确切的数据,我使用的查询是

        $p_plan = $this->ProductPlan->find('all',array(
                                    'conditions'=>array(
                                                'ProductPlan.product_id'=>'Product.product_id'
                                                )                       
                                        )
                                    );  
    $this->set('p_plan', $p_plan);  

如果有人帮助我,我会非常感谢他。提前致谢。

计划关系

class Plan extends AppModel{ 

public $primaryKey='plan_id';

public $hasMany = array(
    'ProductPlan'=>array(
        'className'    => 'ProductPlan',
        'foreignKey'   => 'plan_id' 
    )
);

产品

class Product extends AppModel{ 

public $primaryKey='product_id';

public $hasMany = array(
    'ProductsUser'=>array(
        'className'    => 'ProductsUser',
        'foreignKey'   => 'product_id'  
    ),
    'ProductsUserNode'=>array(
        'className'    => 'ProductsUserNode',
        'foreignKey'   => 'product_id'  
    ),
    'ProductPlan'=>array(
        'className'    => 'ProductPlan',
        'foreignKey'   => 'product_id'  
    )
);

产品计划

class ProductPlan extends AppModel{
var $primaryKey='product_plan_id';
 public $belongsTo = array(
    'Product' => array(
        'className'    => 'Product',
        'foreignKey'   => 'product_id'
    ),
    'Plan' => array(
        'className'    => 'Plan',
        'foreignKey'   => 'plan_id'
    )       

     );
public $hasMany = array(
    'ProductPlansUserNode'=>array(
        'className'    => 'ProductPlansUserNode',
        'foreignKey'   => 'product_plan_id' 
    ),
);

}

4

1 回答 1

6

您应该能够简单地使用“包含”:-

$p_plan = $this->Product->find('all', array(
    'contain' => array('Plan')
));

这将返回您的所有产品及其相关计划。您的 Product 和 Plan 模型需要 hasAndBelongToMany 关系。无需为您的连接表定义模型。

class Product AppModel {
    ...
    public $hasAndBelongsToMany = array('Plan');
    ...
}

class Plan AppModel {
    ...
    public $hasAndBelongsToMany = array('Product');
    ...
}

作为旁注,我个人会避免覆盖 CakePHP 处理主键的默认方式。最好坚持约定和使用id

于 2013-02-18T11:09:06.463 回答