0

我遇到的问题与此处此处的问题非常相似,但这些解决方案并不能帮助我解决我的问题版本。我正在使用 CakePHP 1.3,我试图从视图控制器中调用一些模型函数:

//Class setup
var $uses = array('StudentsTelephone', 'AddressesStudent');

//...

function someFunction(){
    $this->set('telephones', $this->StudentsTelephone->getActiveStudentTelepone($id));
    $this->set('addresses', $this->AddressesStudent->getActiveByStudentId($id));
}

第一个模型函数调用 (StudentsTelephone) 有效,但第二个 (AddressesStudent) 失败。它尝试使用函数名作为 SQL 调用,结果如下:

SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'getActiveByStudentId' at line 1 [CORE\cake\libs\model\datasources\dbo_source.php, line 684]

通过一点调试,我发现正在 AppModel 中查找该函数,并且从未检查过 AddressesStudent。基于这些其他解决方案,它看起来应该是名称中的错字。但是,一切似乎都正确命名。上面的代码如上所述,模型文件是addresses_student.php,类名是 AddressesStudent 并且在我更新 Cake(最近从 1.1 切换到 1.3)之前工作正常。关于可能导致问题的任何建议不是命名错误?或者也许我错过了其他一些命名错误?非常感谢!

编辑:另外,这里的回溯告诉我从未找到模型 PHP 文件:

DboSource::showQuery() - CORE\cake\libs\model\datasources\dbo_source.php, line 684
DboSource::execute() - CORE\cake\libs\model\datasources\dbo_source.php, line 266
DboSource::fetchAll() - CORE\cake\libs\model\datasources\dbo_source.php, line 410
DboSource::query() - CORE\cake\libs\model\datasources\dbo_source.php, line 364
Model::call__() - CORE\cake\libs\model\model.php, line 502
Overloadable::__call() - CORE\cake\libs\overloadable_php5.php, line 50
AppModel::getActiveByStudentId() - [internal], line ??
StudentsController::edit() - APP\controllers\students_controller.php, line 277
Dispatcher::_invoke() - CORE\cake\dispatcher.php, line 204
Dispatcher::dispatch() - CORE\cake\dispatcher.php, line 171
[main] - APP\webroot\index.php, line 83
4

2 回答 2

2

CakePHP 使用“缓存”的自动生成模型

对于 HABTM 关系,CakePHP 将自动为 JOIN 表生成一个“通用”模型(通过创建实例 AppModel),即使连接表存在模型(不要问我为什么!)

CakePHP 将这个自动生成的模型存储在它的缓存中,以便可以在其他位置重用它。

在您的示例中,您尝试使用该AddressesStudent模型。CakePHP 将查找具有该名称的模型,并在缓存中找到具有该名称的模型。然而,这是 HABTM 关系的自动生成模型,而不是您的实际模型!

告诉 CakePHP 使用你的模型而不是自动生成的模型

为了防止 CakePHP 为 HABTM 关系自动生成模型,with为这些关系添加选项;一定要在关系的两边都指定这个(如果你在两边都定义了,那就是

学生模型内部;

$public hasAndBelongsToMany = array(
    'Address' => array(
        // tell CakePHP to use the AddressesStudent model,
        // NOT and auto-generated model
        'with' => 'AddressesStudent',
    ),
);

和/或在地址模型内;

$public hasAndBelongsToMany = array(
    'Student' => array(
        'with' => 'AddressesStudent',
    ),
);

通过这样做,您可以防止缓存包含自动生成的模型。

with:定义连接表的模型名称。默认情况下,CakePHP 会自动为您创建一个模型。使用上面的示例,它将被称为RecipesTag。通过使用此键,您可以覆盖此默认名称。连接表模型可以像任何“常规”模型一样直接访问连接表。

更多信息; hasAndBelongsToMany (HABTM)

于 2013-05-02T21:37:22.760 回答
0

搜索了一整天后,我对这个问题的解决方案是模型文件名中的拼写错误。我用discounts.php了它应该在的地方discount.php

我希望这可以帮助别人!

于 2018-10-29T08:59:25.883 回答