如何在Phalcon框架中订购连接结果


How to order joined results in Phalcon Framework

假设我正在制作一本杂志,其中一个类别(如"体育"、"艺术"等)可以包含几篇文章。因此,我想提取一个特定类别的所有文章。在Phalcon中,我通常这样做:

$category = 'Models'Category::findFirst(array(
    'conditions' => 'id = ?1',
    'bind'       => array(1 => $id)
));

:

foreach ($category->Article as $article) {
    // do something with $article
}

它工作得很好,但是我想对这些文章进行排序——比如按日期排序,按升序排序。我怎么才能做到呢?

你应该在你的for..loop语句中使用get前缀,所以你的代码应该像这样:

foreach ($category->getArticle(array('order' => 'date DESC')) as $article) {
    // do something with $article
}

主文档解释了更多的例子。
试试吧& &;

M2sh的回答都很重要和实际,我只是将发布一个次要的方式,只是使用为文章设计的模型:

$page = 5; // eg. 5th page of results
$limit = 100; // eg. 100 results per page
$articles = 'Models'Articles::find(array(
    'conditions' => 'category_id = :cid:',
    'bind' => array(
        'cid' => $id
    ),
    'order' => 'date DESC, id DESC',
    'limit' => $limit,
    'offset' => $page * $limit
));

在M2sh中也可以使用这些参数

为完整起见,再加一个。我将借用yergo来说明它们的区别:

$page = 5;
$limit = 100;
$articles = 'Models'Articles::query()
    ->where('category_id= :cid:', array('cid' => $id)
    ->orderBy('date DESC, id DESC')
    ->limit($limit)
    ->offset($page * $limit)
    ->query();