2013-02-19 56 views
2

如何在cakephp中查看與其關聯的ID的數據?

Tables 

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

我想要查看的數據與它相關的編號,例如,如果產品有兩個計劃,這將是該產品的名單。這樣

 alpha | delta | 
     a   c 
     b 

視圖代碼是

<table> 
<thead> 
    <tr> 
     <?php foreach ($p as $ps){?> 
     <th> 
      <?php echo __l($ps['Product']['name']);?> 
     </th> 
     <?php }?> 
    </tr> 
</thead>  
    <tbody> 
     <?php foreach ($p as $p1){ 
       foreach($p1['Plan'] as $plan){ 
         debug($plan); 
     ?> 
     <tr> 
      <td> 
       <?php echo __l($plan['name']);?>  
      </td> 
     </tr>   
     <?php } 
        }?> 

    </tbody> 

當我調試$ P1陣列,

array(
'Product' => array(
    'product_id' => '1', 
    'name' => 'Event Manager', 
    'slug' => 'event-manager', 
    'is_visible' => true 
), 
'Plan' => array(
    (int) 0 => array(
     'plan_id' => '1', 
     'name' => 'FREE', 
     'description' => '30 Days Trial', 
     'amount' => '0.00', 
     'expiry_days' => '30', 
     'created' => '2012-01-12 16:51:21', 
     'modified' => '2012-01-12 16:51:22', 
     'PlansProduct' => array(
      'plan_product_id' => '1', 
      'product_id' => '1', 
      'plan_id' => '1' 
     ) 
    ), 
    (int) 1 => array(
     'plan_id' => '2', 
     'name' => 'BRONZE', 
     'description' => '60 Days Trial', 
     'amount' => '10.00', 
     'expiry_days' => '60', 
     'created' => '2012-01-12 16:52:24', 
     'modified' => '2012-01-12 16:52:25', 
     'PlansProduct' => array(
      'plan_product_id' => '2', 
      'product_id' => '1', 
      'plan_id' => '2' 
     ) 
    ) 
) 

我該怎麼辦呢?提前致謝。

回答

0

您必須從控制器傳遞三個變量。 該變量包含三個不同的表格數據。

在需要時使用。

1

我是否理解「產品有很多計劃和計劃有很多產品」(多對多)(http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm)。在這種情況下,您必須在模型中聲明這種關係。

//models/product.php 
class Product extends AppModel{ 
    public $hasAndBelongsToMany = array(
     'Plan' => 
      array(
       'className'    => 'Plan', 
       'joinTable'    => 'ProductPlan', 
       'foreignKey'    => 'id', 
       'associationForeignKey' => 'id', 
       'unique'     => true, 
       'conditions'    => '', 
       'fields'     => '', 
       'order'     => '', 
       'limit'     => '', 
       'offset'     => '', 
       'finderQuery'   => '', 
       'deleteQuery'   => '', 
       'insertQuery'   => '' 
      ) 
    ); 
} 

如果關係是「一對多」,聲明是這樣的:

class Product extends AppModel { 
    public $hasMany = array(
     'Plan' => array(
      'className'  => 'Plan', 
      'foreignKey' => 'product_id' 
     ) 
    ); 
} 

而你需要添加一個名爲「PRODUCT_ID」到「規劃」表的外鍵。

+0

但問題是如何設置我想要的視圖 – usii 2013-02-19 11:37:25

+0

@usii選擇它在控制器中,使用$ this-> render(「nameofview」); – Lobo 2013-02-19 11:41:18

相關問題