0

我正在使用 CakePHP 3.x

我正在关注此处此处的书签教程

我想再添加一项功能,我可以根据标签 id 获取属于同一标签的书签。

我在 BookmarksController 中编写了以下函数

/**
 * Index view by tag method
 *
 * @return void
 */
    public function index_by_tag($tag_id) {
        $conditions = [
            'Bookmarks.public' => true,
        ];
        $this->paginate = [
            'conditions' => $conditions,
            'contain' => [
                'Users' => function ($q) {
                   return $q
                        ->select(['username', 'id']);
                }
            ],
            'order' => [
                'Bookmarks.updated' => 'desc', 
                'Bookmarks.id' => 'desc'
            ]
        ];
        $this->set('bookmarks', $this->paginate($this->Bookmarks));
    }

我应该如何更改$conditions以便只能检索属于同一标签的那些书签?

请记住,书签和标签是多对多的关系。

更新1

我发现了使用matching. 如果我使用query builder.

请参阅http://book.cakephp.org/3.0/en/orm/query-builder.html#using-matching-when-finding-results

但是,没有提到如何matching与分页一起使用。

更新2

我刚刚意识到已经有一个自定义查找器方法可以满足我的要求,但它不适用于分页。

http://book.cakephp.org/3.0/en/tutorials-and-examples/bookmarks/intro.html#getting-bookmarks-with-a-specific-tag

4

1 回答 1

0

答案在于更改tagsBookmarksController.php 中的操作

最初在教程中,标签操作如下所示:

public function tags() {
    $tags = $this->request->params['pass'];

    $bookmarks = $this->Bookmarks->find('tagged', [
        'tags' => $tags
    ]);

    $this->set(compact('bookmarks', 'tags'));
}

改变在于改变如何定义$bookmarks

public function tags() {
    $tags = $this->request->params['pass'];

    // you can call custom finder methods within paginate
    // the link is at http://book.cakephp.org/3.0/en/controllers/components/pagination.html#using-controller-paginate
    // scroll down just a bit to look at custom finder methods
    $this->paginate = [
        'finder' => [
            'tagged' => [
                'tags' => $tags
            ]
        ]
    ];

    $bookmarks = $this->paginate($this->Bookmarks);

    $this->set(compact('bookmarks', 'tags'));
}
于 2014-11-02T06:10:30.580 回答