【发布时间】:2015-06-16 08:45:04
【问题描述】:
我对 HABTM 模型有疑问。当我尝试获取任何相关模型 f.e.像这样:
$this->Tagi->find('first');
我没有得到任何关联模型的结果。结果如下所示:
array(
'Tagi' => array(
'id' => '1',
'nazwa' => 'sth'
),
'Instytucje' => array()
)
我确定应该有结果,我已经仔细检查过,甚至
$this->Tagi->getDataSource()->getLog(false, false)
显示正确的查询,获取正确的结果。 如果您有任何想法,请给我一个提示。
塔吉模型:
public $hasAndBelongsToMany = array(
'Instytucje' =>
array(
'className' => 'Instytucje.Instytucje',
'joinTable' => 'instytucje-tagi',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'instytucja_id',
'unique'=> true
)
);
Instytucje 模型:
public $hasAndBelongsToMany = array(
'Tagi' =>
array(
'className' => 'Instytucje.Tagi',
'joinTable' => 'instytucje-tagi',
'foreignKey' => 'instytucja_id',
'associationForeignKey' => 'tag_id',
'unique'=> true
)
);
编辑: 主要问题是HABTM引用AppModel导致错误:
Error: Table app_models for model AppModel was not found in datasource prod.
可以通过在AppModel中添加$useTable来绕过,这会导致之前的问题。
已解决
当使用远远超出此 Cake 用途的命名约定时,您已使用第三个模型,$useTable 指向参考表。
此外,正确地将 Cake 指向插件内的类也很重要。
【问题讨论】:
-
您能否将生成的 SQL 包含在内,以便我们可以看到它的工作原理?您还检查过您的模型没有使用
afterFind()回调来更改数据吗? -
我检查了生成的 SQL,它获取了正确的结果:'SELECT
Instytucje.id,Instytucje.nazwa, ****,AppModel.instytucja_id,AppModel987654337epf987654339 @ $ 987654340 @epf987654341instytucje-tagiASAppModelON(tag_id987654345 @AppModel987654347instytucja_id987654347instytucja_id987654347instytucja_id987654347instytucja_id987654348@.id) ' **** - 代表表格的其他字段(很长的列表)。 -
您的查询将 Tagi 别名为
AppModel是否有原因?这对我来说看起来不正确,可能是导致问题的原因。 -
不知道,你知道它为什么这样做吗?它不是故意命名为 AppModel。
-
它可能将 instytucje-tagi 别名为 AppModel,因为我没有显示“Instytucje”和“Tagi”之间关系的表格模型。
标签: cakephp cakephp-2.0 has-and-belongs-to-many