如何在CakePHP中实现“相关帖子”元素?

时间:2016-10-21 02:39:56

标签: cakephp cakephp-2.5

我的主要模型是Post,它填充了许多不同的信息字段(名称,名称,状态,创建,修改等),其中之一是它与Category模型的关系。 (帖子属于类别,类别有很多帖子。)

到目前为止一切正常。我可以保存和编辑category_id,每个类别都有一个索引,每个类别都属于它。一切都很好。

现在我需要实现一个特殊的额外功能,但我对可能解决方案的所有搜索都是徒劳的。我有一些想法,但我不知道如何实现这些,我不确定在这种情况下最佳做法是什么。

我需要在视图视图中的帖子信息下方添加一些“相似/相关帖子”模块,从中加载一些基本信息(名称,名称,创建日期等) 3个与当前帖子相同类别的随机帖子。

我以为我可以尝试在元素中使用find('all')函数(将category_id作为视图操作中的变量加载)。

这是我的控制者:

class PostsController extends AppController {

    public function view($id) {

        if (!$id) {
            throw new NotFoundException(__('Invalid post.'));
        }

        $post = $this->Post->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Post not found.'));
        }

        $this->set('post', $post);
    }
}

在Post模型中我有:

class Post extends AppModel {
    public $belongsTo = array('Category');
}

在分类模型中,我有:

public $hasMany = array(
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'category_id',
        'dependent' => false
    )
);

目前我只需要在视图视图中加载那些“相关帖子”,但我不确定以后我是否需要这样做。 (这就是为什么我在模块的元素中思考。)

1 个答案:

答案 0 :(得分:3)

在视图中编写查询不好,要么你可以使用帮助器,要么可以直接在控制器中完成,在控制器中你可以尝试下面的代码:

class PostsController extends AppController {

    public function view($id) {

        if (!$id) {
            throw new NotFoundException(__('Invalid post.'));
        }

        $post = $this->Post->findById($id);
        if (!$post) {
            throw new NotFoundException(__('Post not found.'));
        }

        $relatedPosts = $this->Post->find('all', array('conditions' => array('Post.category_id' => $post['Post']['category_id'], 'NOT' => array('Post.id' => $id)), 'limit' => 3));

        $this->set('relatedPosts', $relatedPosts);
        $this->set('post', $post);
    }
}

然后在你的视图中你可以检查!empty($ relatedPosts),然后你可以在$ relatedPosts上循环并显示你想要显示的任何字段。