【问题标题】:CakePHP no data from related modelCakePHP 没有来自相关模型的数据
【发布时间】:2013-01-10 13:52:28
【问题描述】:

我有 2 个相互关联的模型。

class AccountModel extends AppModel {

    public $name = 'Account';
    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey'   => 'user_id',

        ),
    );
}

class UserModel extends AppModel {

    public $name = 'User';
    public $hasMany = array(
        'Account' => array(
            'className' => 'Account',
            'foreignKey'   => 'user_id',

        ),
    );

}

表格: 帐户 -ID -用户身份 - 其他领域...

用户 -ID - 其他领域...

从一个模型请求数据只返回该模型的数据,不返回相关数据。 我想请求具有 id 的模型用户并返回所有用户数据和相关的帐户数据。 与使用一个参数请求 Account-model 相同,而不是 account_id 或 user_id,并返回所有 Account-data 和相关的 User-data。

$User = $this->Account->findByField($param);

只返回array('Account' => array(...)) 和

$User = $this->User->findById($id);

只返回array('User' => array(...)) 但没有请求返回array('User' => array(...), 'Account' => array(..))

我将如何获取所有相关数据?

问候 米。

【问题讨论】:

  • $this->Account->recursive = 2;没有效果,与 $this->Account->find('first', array('conditions' => array('field' => $param), 'recursive' => 2)); 相同;
  • 转到here 并搜索saveAll($data)。这就是保存记录及其相关记录的内容,这正是您想要的。祝你好运!
  • 这正是我想要的?我要寻找,而不是保存。 ://
  • 安装 CakePHP 的调试工具工具栏 (github.com/cakephp/debug_kit) 并查看为您的查询生成的 SQL。

标签: model relationship cakephp-2.1


【解决方案1】:

FindBy{fieldname} 不允许使用递归选项(如 cakephp 文档中定义的 findBy<fieldName>(string $value[, mixed $fields[, mixed $order]]); )。

为了通过关系获取递归数据,你应该使用find方法。

$userData = $this->User->find('first', array(
    'conditions' => array('id' => $userId),
    'recursive' => 1,
));

如果没有返回数据,请检查以下内容: - 是否传递了有效的用户 ID? - 两个表中是否有给定 userId 的数据? - 在您尝试运行 Find 查询时,模型是否正确加载?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多