[英]Link the same model twice to another model in CakePhp
這可能是一個非常基本的問題,但是我無法解決這個問題。
在我的應用程序中,我的用戶擁有多個具有不同目的的地址。 例如,用戶可以具有一個地址和一個發票地址。 我想將兩個地址存儲在同一表(地址模型)中,然后將它們分配給一個用戶。
各個模型如下所示:
地址:
public $belongsTo = array(
'Address' => array(
'className' => 'Address',
),
'InvoiceAddress' => array(
'className' => 'Address',
),
);
和用戶:
public $hasOne = array(
'Address' => array(
'className' => 'Address',
),
'InvoiceAddress' => array(
'className' => 'Address',
),
);
當一個用戶有一個地址時,我會將一個user_id作為外鍵添加到Address模型中,並完成此操作。 但是顯然,CakePhp必須做些不同的事情才能區分地址和發票地址。
在我看來,解決方案就像在User表中添加address_id和invoice_address_id一樣,但是我似乎無法以任何方式使其工作。
如果要在用戶表中添加相關字段,則最好以以下格式添加它們: address_user_id
和invoice_address_user_id
。 然后,您的用戶模型中必須具有一個類似於以下內容的belongsTo關系:
public $belongsTo = array(
'Address' => array(
'className' => 'Address',
'foreignKey' => 'address_user_id',
),
'InvoiceAddress' => array(
'className' => 'Address',
'foreignKey' => 'invoice_address_user_id',
),
);
因此,當您執行以下命令時, $this->User->find('all');
結果將是
$result = array(0 =>
array('User' => array(...),
'Address' => array(...), // it will bring only one address row
'InvoiceAddress' => array(...) // it will bring only one address row
),
1 => ...
2 => ...
);
然后,在您的地址模型中,您必須添加的關系是:
public $hasOne = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'address_user_id',
),
'InvoiceUser' => array(
'className' => 'User',
'foreignKey' => 'invoice_address_user_id',
)
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.