2013-09-23 43 views
1

我有三個表:CakePHP的2間型關係的多個外鍵

  • 客戶
  • 價格
  • 項目

架構例如:

客戶有一個客戶編號

商品可以有多個價格屬於不同的客戶

一價屬於一個項目,一個客戶

產品 - 型號:

class Item extends AppModel { 
    public $hasOne = 'Price'; 
    //... 
} 

價格,型號:

class Price extends AppModel { 

    public $belongsTo = array(
     'Item' => array(
      'className' => 'Item', 
      'foreignKey' => 'id' 
     ) 
    ); 

所以現在發生的情況是:對於3個不同的客戶,一個項目有3個不同的價格秒。我得到自動的所有項目(一個項目的3倍),但我想只有在客戶(通過CUSTOMER_NUMBER確定當前登錄的物品,出現在該表中的字段:

  • 客戶
  • 價格

任何建議,謝謝

回答

2

首先亮相,遵循CakePHP的約定:你customers表應該有一個id列,您prices表應該有一個。列,這是您的customers表的外鍵。如果您需要一個人性化的「客戶編號」,與客戶的編號分開,用於標識該客戶,那麼它可以是客戶表格中的額外字段,但不應將其複製到價格表中。

其次,您已在您的物料模型中定義了物料具有一個價格。實際上並非如此 - 一個項目有很多價格 - 每個客戶一個。

你在這種情況下的後果是HasMany through關係。閱讀文檔 - 你會像這樣結束:

// Customer.php 
class Customer extends AppModel { 
    public $hasMany = array(
     'Price' 
    ); 
} 

// Item.php 
class Item extends AppModel { 
    public $hasMany = array(
     'Price' 
    ); 
} 

// Price.php 
class Price extends AppModel { 
    public $belongsTo = array(
     'Customer', 'Item' 
    ); 
} 

你的價格表都需要一個customer_id柱和item_id列。

接下來,當爲當前登錄的客戶返回項目時,您可以在您的Price模型中查找並加入您的項目模型,其中price.customer_id等於相關客戶的ID。

+0

非常感謝你解決了我的問題..! – user2610087