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表是正确的但是我没有得到确切的数据,我使用的查询是
$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'
),
);
}
答案 0 :(得分:6)
您应该只需使用'包含': -
$p_plan = $this->Product->find('all', array(
'contain' => array('Plan')
));
这将返回您的所有产品及其相关计划。您的产品和计划模型需要hasAndBelongToMany关系。无需为连接表定义模型。
class Product AppModel {
...
public $hasAndBelongsToMany = array('Plan');
...
}
class Plan AppModel {
...
public $hasAndBelongsToMany = array('Product');
...
}
作为旁注,我个人会避免重写CakePHP处理主键的默认方式。最好坚持使用约定并使用id
。