CakePHP 2模型关系多个外键
我有三张桌子:CakePHP 2模型关系多个外键,php,cakephp,cakephp-model,Php,Cakephp,Cakephp Model,我有三张桌子: 顾客 价格 项目 模式示例: 客户有一个客户号码 商品可以有多个属于不同客户的价格 一个价格属于一个项目和一个客户 项目型号: class Item extends AppModel { public $hasOne = 'Price'; //... } class Price extends AppModel { public $belongsTo = array( 'Item' => array(
- 顾客
- 价格
- 项目
class Item extends AppModel {
public $hasOne = 'Price';
//...
}
class Price extends AppModel {
public $belongsTo = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'id'
)
);
价格模式:
class Item extends AppModel {
public $hasOne = 'Price';
//...
}
class Price extends AppModel {
public $belongsTo = array(
'Item' => array(
'className' => 'Item',
'foreignKey' => 'id'
)
);
因此,现在发生的是:一个项目有3个不同的价格为3个不同的客户。我自动获取所有项目(一个项目3次),但我只需要当前登录客户的项目(由客户编号标识,此表中显示的字段:
- 顾客
- 价格
有什么建议吗?谢谢。首先,遵循CakePHP惯例:您的
客户
表应该有一个id
列。您的价格
表应该有一个客户id
列,这是客户
表的外键。如果您需要一个人性化的“客户编号”,请分开根据用于标识该客户的客户id,它可以是客户表中的一个额外字段,但不应复制到价格表中
第二,你已经在你的商品模型中定义了一个商品只有一个价格,但事实并非如此——一个商品有很多价格——每个顾客有一个价格
在这种情况下,你追求的是一种关系。阅读该文档-你最终会得到如下结果:
// 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\u id
列和一个item\u id
列
接下来,当为当前登录的客户返回项目时,您可以在加入到项目模型的价格模型上进行查找,其中Price.Customer_id等于相关客户的id