CakePHP选择多对多(HABTM)记录
在创建了两个类之间的多对多(HABTM)关系(如下面的代码所示)之后,我希望看到包括相关记录在内的结果,但由于某种原因,这并没有发生 型号CakePHP选择多对多(HABTM)记录,php,cakephp,many-to-many,has-and-belongs-to-many,Php,Cakephp,Many To Many,Has And Belongs To Many,在创建了两个类之间的多对多(HABTM)关系(如下面的代码所示)之后,我希望看到包括相关记录在内的结果,但由于某种原因,这并没有发生 型号 App::uses('AppModel', 'Model'); class NewsCategory extends AppModel{ public $hasAndBelongsToMany = array('News'); } App::uses('AppModel', 'Model'); class News extends AppModel{
App::uses('AppModel', 'Model');
class NewsCategory extends AppModel{
public $hasAndBelongsToMany = array('News');
}
App::uses('AppModel', 'Model');
class News extends AppModel{
public $hasAndBelongsToMany = array('NewsCategory');
}
我创建了一个名为“news\u news\u categories”的表,两个表的id都是
控制器
this->data = $this->News->find('first', array('conditions' => array('News.id' => $id)));
上述代码的结果不包括相关的NewsCategory记录
在花了几个小时试图实现这一点后,我无法完成这一点
我错过了什么
提前谢谢大家
更新 当我使用
echo $this->element('sql_dump');
结果未显示此关系的任何查询(或加入)。CakePHP只是忽略$HasandBelongToMany配置 我认为CakePHP约定存在问题。因此,您只需在模型中输入use表名。 像
同时阅读CakePHP您必须遵守CakePHP的编码约定,否则您的代码将无法按预期工作,或者您将不得不使用肮脏的技巧,如
$useTable=etc
您的问题是HABTM的表名应该是
1.所有小写字母
2.它应该有两个表名(复数)
3.复数表格名称(即单词)应按字母顺序排列/
4.表名之间应该有下划线
根据规则,您的表名应为news\u news\u categories
还要确保在表
news\u news\u categories
中有外键,如news\u id
和news\u category\u id
。并确保在news\u news\u categories
表中没有任何主键(如id),因为这两个字段组合作为主键工作 终于找到了解决办法。基本上我做了以下步骤:
this->data = $this->News->find('first', array('conditions' => array('News.id' => $id)), 'contain' => array('NewsCategory'));
$this->data['News']['NewsCategories'] //or anything like that
$this->data['NewsCategory']
(并且没有像我第一次假设的那样嵌套在新闻结果数组中)
谢谢大家。我希望这对以后的其他人有所帮助。对不起,这是一个打字错误(在我原来的问题上修复了它)。如您所述,该表的名称已小写。为什么联接表(news\u news\u categories)不能有id列?我问,因为它有id列,我没有任何问题,创建记录。。。只有当选择它不工作时,顺便说一句,我才让它工作,不需要从关系表中删除id列。谢谢你的帮助!为什么我要将我的NewsCategory模型表命名为“news\u news\u categories”?“news\u news\u categories”应该是“news\u categories”,这是一个类型错误。实际上这不是问题所在,因为所有表都遵循约定。无论如何,谢谢你的支持
$this->data['News']['NewsCategories'] //or anything like that
$this->data['NewsCategory']