php - CakePHP 2 模型关系多个外键

标签 php cakephp cakephp-model

我有三个表:

  • 客户
  • 价格
  • 项目

架构示例:

客户有客户编号

商品可以有属于不同客户的多个价格

一个价格属于一件商品和一位客户

商品型号:

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 标识,该字段出现在此表中:

  • 客户
  • 价格

有什么建议吗?谢谢。

最佳答案

首先,遵循 CakePHP 约定:您的 customers 表应该有一个 id 列。您的 prices 表应该有一个 customer_id 列,它是您的 customers 表的外键。如果您需要一个人性化的“客户编号”,与客户 ID 分开,用于识别该客户,那么它可以是客户表中的一个额外字段,但不应该重复到价格表中。

其次,您在 Item 模型中定义了 Item hasOne Price。这实际上是不正确的 - 一件商品有多种价格 - 每个客户都有一个价格。

在这种情况下你所追求的是 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.customer_id 等于相关客户的 ID。

关于php - CakePHP 2 模型关系多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18955266/

相关文章:

php - InnoDB MySQL 表中的重音不敏感搜索!

php - 使用php将表单更新错误发布到mysql

php - 针对 JSON 模式的 JSON 验证

cakephp - CakePHP 的博客教程中当前时间和修改时间是如何保存的?

javascript - Cakephp 中的可重复子表单

php - CakePHP 可包含 : Loading too much relations?

php - 使用 while 循环从数据库填充数组

php - preg_match() 期望参数 2 为字符串,在 CakePHP 中给出错误的对象

php - 在 cakePHP 中创建一个与模型无关的表单

php - CAKEPHP - 自引用表覆盖变量