gpt4 book ai didi

php - 在 CakePHP 上设置关联

转载 作者:行者123 更新时间:2023-11-30 01:19:12 25 4
gpt4 key购买 nike

我开始尝试学习 CakePHP 和 MVC。

我有一个数据库,其中有很多表,我正在尝试关联这些表,并且一直在阅读 the docs .

以下是我拥有的一些表格的解释:

客户表,具有字段:

  • id
  • 姓名
  • 货币
  • risk_code_id(这是 risk_codes 表的外键)
<小时/>

帐户表:

  • id
  • client_id
  • ...与每个帐户相关的更多字段
<小时/>

risk_codes 表:

  • id
  • 姓名

我目前只有一个供客户使用的模型,如下所示:

<?php
class Client extends AppModel {
public $hasMany = 'Account';
public $validate = array(
'title' => array(
'rule' => 'notEmpty'
),
'body' => array(
'rule' => 'notEmpty'
)
);
}

这会检索与客户相关的帐户。

如何将 risk_codes 表与 clients 关联?我是否需要为risk_codes 制作另一个模型并在那里定义关联?显而易见,每个客户都有一个风险代码。

最佳答案

查看http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html .

由于关系客户 ->risk_code 是“多对一”,我们说“客户属于风险代码”。因此,您必须以两种不同的方式进行设置:

客户端模型

public $belongsTo = array(
'RiskCode' => array(
'className' => 'RiskCode',
'foreignKey' => 'risk_code_id'
)
);

风险代码模型

public $hasMany = array(
'Client' => array(
'className' => 'Client',
'foreignKey' => 'risk_code_id'
)
);

在建立这些关系时,您可以设置许多其他选项,因此请查看 CookBook 以获取详细信息。 :)

关于php - 在 CakePHP 上设置关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18744008/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com