【发布时间】:2011-06-17 17:22:54
【问题描述】:
现在我已经尝试解决这个问题几个小时了,我一直在尝试谷歌和文档并一遍又一遍地阅读它,但我似乎无法理解它。
让我试着解释一下我在做什么,但要简化项目,假设我正在用 cakePHP 制作博客。我得到了这 3 个表,以便我们只使用所需的字段。
Table: posts
Desc: This table store all our posts
Fields:
postid - Identifier for the post
title - The posts title
Table: sections
Desc: this table contains categories
Fields:
sectionid - Identifier
sectionname - Name
Table: postlinks
Desc: this table store relations between posts and categories.
Fields:
postid – Post ID to determine what post is linked to what section
sectionid – Section ID to determine the section this post belong to
现在让我通过一个带有常规 php 和 SQL 代码的示例来解释我想用 cakePHP 实现什么:
(请注意,此代码是在旅途中编写的,可能无法正常工作,但它应该让您了解我正在尝试做什么)
<?php
/**
*Block of code to fetch all posts
*/
while ( $rows = mysql_fetch_array($query) )
{
$postid = $rows['postid'];
/** Join postlinks and sections **/
$sql = “SELECT sections.*, postlinks.* FROM postlinks
INNER JOIN sections
ON postlinks.sectionid = sections.sectionid
WHERE postlinks.postid = '$postid'”;
$query = mysql_query($sql);
print “-- TITLE --”;
print “-- CONTENT --”;
print “Posted in “;
/** Loop all categories **/
while ( $rows = mysql_fetch_array($query) )
{
print $rows['sectionname'] . “ “;
}
}
?>
现在我将尝试用文字解释我想要实现的目标:
当访问者在浏览网页时,进入网站的博客部分,我希望列出 X 个最新的帖子,这些帖子可以放在多个类别中,我们会将所有类别链接存储在一个单独的表格,这是我被塞满的地方,我可以设法将链接取出,但我似乎无法加入表格并循环出名称。
希望有人能阐明我遇到的这个问题,或者指出我正确的方向和/或向我展示示例代码。
如前所述,我一直在阅读文档,并尝试寻找答案,但
【问题讨论】:
-
您所说的是帖子和类别之间的普通hasAndBelongsToMany relationship。你已经正确设置了吗?如果是这样,请再次说明问题所在。我无法从你的描述中弄清楚。
-
我同意 deceze。我建议您遵循 cakephp 约定:book.cakephp.org/view/903/Model-and-Database-Conventions.