【问题标题】:How to join database tables using cakePHP?如何使用 cakePHP 连接数据库表?
【发布时间】: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 个最新的帖子,这些帖子可以放在多个类别中,我们会将所有类别链接存储在一个单独的表格,这是我被塞满的地方,我可以设法将链接取出,但我似乎无法加入表格并循环出名称。

希望有人能阐明我遇到的这个问题,或者指出我正确的方向和/或向我展示示例代码。

如前所述,我一直在阅读文档,并尝试寻找答案,但

【问题讨论】:

标签: php sql cakephp


【解决方案1】:

关联被实现为 cakephp 中的连接。 请遵循 HABTM 的概念,即“拥有并属于许多人” 在你的模型关联中声明。

在你的 cakephp 查询中声明关联。

递归 -> -1 或 0 或 1 或 2

要了解更多有关协会的信息,请访问此链接enter link description here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多