现在我一直在努力解决这个问题几个小时了,我一直在尝试谷歌和文档,一遍又一遍地阅读,但我似乎无法理解它。如何使用cakePHP连接数据库表?
让我试着解释一下我在做什么,但是简化项目,假设我正在用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
现在让我解释一下我想要实现使用CakePHP什么通过展示与普通PHP和SQL代码的例子:
(注意此代码在旅途中写起来可能无法正常工作,但它应该给你什么,我试图做)
<?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'] . “ “;
}
}
?>
一个想法,现在我会尽量用言语什么,我试图达到解释:
当访问者浏览网页PAG e,然后进入该网站的博客部分,我希望列出X个最新帖子,这个帖子可以放在多个类别中,我们将所有类别链接存储在一个单独的表格中,这里是我塞满的地方,我可以设法获得链接,但我似乎无法加入表格并圈出名称。
希望有人可以对这个问题提出一些看法,我可以让我指出正确的方向和/或给我一个示例代码。
如前所述我一直在阅读文档,我试图寻找答案,但
什么你所谈论的是决胜的磨[hasAndBelongsToMany关系](http://book.cakephp.org/view/1044/hasAndBelongsToMany-HABTM)之间的职位和类别。你已经正确设置了吗?如果是这样,请再次解释问题是什么。我无法从你的描述中弄清楚。 – deceze 2011-01-29 11:47:36