【问题标题】:Yii limit on related model while queryingYii 查询时对相关模型的限制
【发布时间】:2012-04-12 13:58:44
【问题描述】:

我遇到了限制问题。我使用的代码如下:

$model = PostCategory::model();
  $record = $model->with(array(
    'posts'=>array(
      'order'=>'posts.createTime DESC',
      'limit'=>3,
))->findByPK($id);

我想限制出于分页目的而查询的帖子。我也试过添加

'together'=>true

在限制之后,这也无济于事。

感谢任何帮助。

【问题讨论】:

  • +1 好问题,我检查了执行的查询,limit 永远不会被附加到查询中。

标签: php sql yii limit


【解决方案1】:

这肯定行得通,刚刚测试过:

$model = PostCategory::model();
$record = $model->with(array(
  'posts'=>array(
     'order'=>'posts.createTime DESC',
  ))->findByPK($id,
             array('limit'=>3,'together'=>true) // adding this works
);

【讨论】:

  • 如果您需要任何说明,请告诉我,以及它对您的影响。
【解决方案2】:

这是parameterized named scopes 上的维基。

但是如果你想在使用关系查询时过滤 RELATED 表中的记录,那么你应该使用 defaultScope()。

这是defaultScope 上的一个 wiki,它还展示了如何在不需要 defaultScope 时绕过它。

【讨论】:

    【解决方案3】:

    您可以在 Post 模型中添加范围并使用

    PostModel.php

    public function recent( $limit = 3 ) {
    
        $this->getDbCriteria()->mergeWith(array(
            'order' => $this->getTableAlias(false, false).'.createTime DESC',
            'limit' => (int) $limit,
        ));
    
        return $this;
    }
    

    MyController.php

    $record = $model->with('posts:recent')->findByPK($id);
    

    而且你的代码干净易读。

    查看有关范围的更多信息 http://www.yiiframework.com/doc/guide/1.1/en/database.ar#named-scopes

    这个论坛发布了如何使用 ->with 为您的范围提供参数 http://www.yiiframework.com/forum/index.php/topic/23358-parameterized-vs-named-scopes-question-using-yii-118/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      • 2018-09-13
      相关资源
      最近更新 更多