【发布时间】:2011-09-22 15:18:49
【问题描述】:
我有 2 个模型需要通过 habtm 关系链接,具有以下表结构:
类别:
id | name | ..
-----------------------
1 | test | ..
帖子:
id | name | other_id | ..
---------------------------------
1 | test | 5 | ..
CATEGORIES_POSTS:
id | category_id | other_id
--------------------------------
1 | 1 | 5
我需要从类别方面获取帖子,但似乎无法正确设置 habtm 关系。到目前为止我没有提到的重要一点是 Post-model 中使用的 id 不是 id 而是 other_id。这是我迄今为止尝试过的(全部在类别模型中):
-
将 associationForeignKey 设置为 'other_id'
在 sql-query 中它有:
CategoriesPost.other_id = Post.id片段 -> 错误的关系(应该是CategoriesPost.other_id = Post.other_id -
将associationForeignKey设置为false并添加条件
CategoriesPost.other_id = Post.other_id现在sql片段是
CategoriesPost. = Post.id--> sql错误 -
将关联外键设置为
CategoriesPost.other_id = Post.other_id嗯 .. 这也是一个错误,因为 Cake 将输入作为 1 个字段:
CategoriesPost.other_id = Post.other_id = Post.id
我知道我可以通过 2 个 hasMany 链接实现关联,但这给了我很多查询而不是 1 个
提前致谢!
【问题讨论】:
-
CATEGORIES_POST 是表的名称吗? Cake 会尝试使用 CATEGORIES_POSTS。否则,associationForeignKey = 'other_id' 的错误信息是什么?
-
你是对的连接表名称。我在上面更正了它并添加了我的尝试结果..
-
只是出于好奇,您为什么不遵守 Cake 的约定?也就是说,链接
Post.id和Post.other_id有什么区别?在我看来,如果他们是 1-1,你可以省去很多麻烦。 -
另外,您尝试使用哪个模型执行
find()?邮政?或类别?为清楚起见尝试 #2,您是否使用数组表示法或字符串表示condition? -
对于第一个问题:我遇到问题的数据库结构具有不同的结构。很难解释。每篇文章都会生成几个不同的“出版物”(例如语言)。所以 real 模型是出版物。该模型的内容是通过导出所有可能版本的帖子创建的-> 我有一个 publication_id 和一个 post_id .. 正如我所说:难以解释 --- 第二个问题:错误 .. 我认为是字符串,但不是很一定要诚实
标签: cakephp has-and-belongs-to-many