簡體   English   中英

如何在cakephp中通過外鍵查找數據?

[英]How to find data through foreign key in cakephp?

 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' 
    ),
);

}

你應該只能使用'包含': -

$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM