我遇到HABTM模型的问题。当我尝试获取任何相关的模型f.e.像这样:
$this->Tagi->find('first');
我没有得到相关模型的任何结果。结果如下所示:
array(
'Tagi' => array(
'id' => '1',
'nazwa' => 'sth'
),
'Instytucje' => array()
)
我确信应该有结果,我已经仔细检查过,甚至
$this->Tagi->getDataSource()->getLog(false, false)
显示正确的查询,即获取正确的结果。 如果您有任何想法,那么错误请给我一个提示。
Tagi模型:
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指向插件内的类非常重要。
答案 0 :(得分:1)
我认为你的问题与你没有使用CakePHP的命名约定有关。从生成的查询的外观来看,Cake不知道如何正确地为连接表添加别名,因此在查询中获得AppModel
别名。我怀疑当Cake尝试从查询中构建结果数组时,这会导致问题。
这可能不起作用,但尝试为名为InstytucjeTagi
的联接表创建模型;然后使用with
键更新您的关联以使用它: -
Tagi模型:
public $hasAndBelongsToMany = array(
'Instytucje' =>
array(
'className' => 'Instytucje.Instytucje',
'joinTable' => 'instytucje-tagi',
'with' => 'InstytucjeTagi',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'instytucja_id',
'unique'=> true
)
);
Instytucje模型:
public $hasAndBelongsToMany = array(
'Tagi' =>
array(
'className' => 'Instytucje.Tagi',
'joinTable' => 'instytucje-tagi',
'with' => 'InstytucjeTagi',
'foreignKey' => 'instytucja_id',
'associationForeignKey' => 'tag_id',
'unique'=> true
)
);
如果这不能解决,请尝试使用Tagi
模型中的afterFind()
callback来检查Cake返回的内容: -
afterFind($results, $primary = false) {
parent::afterFind($results, $primary);
// Print out the $results to check what Cake is returning.
debug($results);
return $results;
}