【问题标题】:How to add posts to homepage cakephp?如何将帖子添加到主页 cakephp?
【发布时间】:2014-02-25 02:20:42
【问题描述】:

我是 cakephp 新手。所以我想问你,如何将帖子添加到主页。 我通过本教程创建了帖子http://book.cakephp.org/2.0/en/getting-started.html#blog-tutorial

接下来我该怎么做?

我试图用谷歌搜索它,但没有任何效果。

谢谢。

home.ctp

<h1>Blog posts</h1>
<table>
    <tr>
        <th>Id</th>
        <th>Title</th>
        <th>Created</th>
    </tr>

    <!-- Here is where we loop through our $posts array, printing out post info -->

    <?php foreach ($posts as $post): ?>
    <tr>
        <td><?php echo $post['Post']['id']; ?></td>
        <td>
            <?php echo $this->Html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
        </td>
        <td><?php echo $post['Post']['created']; ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($post); ?>
</table>

【问题讨论】:

  • 如果你得到"Error: Call to a member function find() on a non-object,你可能缺少$uses = array('Post');。您可以粘贴 PostsController 的内容吗?
  • 如果他遵循 Cake 命名约定,那么他就不需要 $uses。请检查您的模型名为Post.php,您的控制器名为PostsController.php,并分别具有App::uses('AppModel', 'Model');App::uses('AppController', 'Controller');

标签: cakephp posts


【解决方案1】:

您必须将主页重定向到PostsControllerindex()

转到您的routes.php 文件并更改此行:

Router::connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));

对于这个:

Router::connect('/', array('controller' => 'posts', 'action' => 'index'));

(假设您的index() 实际上包含您所有帖子的列表)

Router::connect 将捕获用户尝试转到第一个参数上的 url,并将其重定向到控制器中第二个参数上的操作

【讨论】:

  • 我试过这个,但后来我得到一个错误“错误:调用非对象文件上的成员函数 find():C:\wamp\www\cakephp\app\Controller\PostsController .php 行:7"
  • 这是您的控制器方法(可能是index())的问题,而不是重定向的问题。无论如何,您可以在引发此错误的地方发布您的代码吗?所以我们可以帮助你
  • 对不起,我的错误。谢谢,它有效,但是如果我想在主页上显示帖子和食谱,那我该怎么办?
  • 您可以使用$uses 变量在控制器上导入您想要的任何模型,或者使用$this-&gt;loadModel('Recipe'); 即时导入。然后你可以像往常一样在这个模型上进行查找
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-24
  • 2021-04-08
  • 2013-05-24
  • 2018-03-04
  • 1970-01-01
相关资源
最近更新 更多