1

在一个动作中使用 symfony && 学说 1.2,我尝试为用户显示排名最高的网站。

我做了:

 public function executeShow(sfWebRequest $request)
  {
    $this->user = $this->getRoute()->getObject();
    $this->websites = $this->user->Websites; 
  }

唯一的问题是它返回一个包含所有网站的 Doctrine 集合,而不仅仅是排名靠前的网站。

我已经设置了一个方法(getTopRanked()),但如果我这样做:

$this->user->Websites->getTopRanked()

它失败。

如果有人有想法改变 Doctrine 集合以仅过滤排名靠前的。

谢谢

PS:我的方法看起来像(在 websiteTable.class.php 中):

   public function getTopRanked()
{
  $q = Doctrine_Query::create()
       ->from('Website')
      ->orderBy('nb_votes DESC')
       ->limit(5);
  return $q->execute();

}
4

4 回答 4

5

我宁愿在方法之间传递 Doctrine_Query :

//action
public function executeShow(sfWebRequest $request)   
{
   $this->user = $this->getRoute()->getObject();
   $this->websites = $this->getUser()->getWebsites(true);  
}

//user
  public function getWebsites($top_ranked = false)
  {
    $q = Doctrine_Query::create()
     ->from('Website w')
     ->where('w.user_id = ?', $this->getId());
    if ($top_ranked)
    {
      $q = Doctrine::getTable('Website')->addTopRankedQuery($q);
    }
    return $q->execute();
  }

//WebsiteTable
public function addTopRankedQuery(Doctrine_Query $q)
{
  $alias = $q->getRootAlias();
  $q->orderBy($alias'.nb_votes DESC')
    ->limit(5)
  return $q
}
于 2011-01-09T19:35:38.790 回答
1

如果 getTopRanked() 是您的用户模型中的一个方法,那么您可以使用$this->user->getTopRanked()

于 2011-01-09T05:17:10.447 回答
1

在您的情况下, $this->user->Websites 包含所有用户网站。据我所知,没有办法过滤现有的学说集合(除非您将遍历它并选择有趣的元素)。

我只需在 User 类中实现 getTopRankedWebsites() 方法:

class User extends BaseUser
{
  public function getTopRankedWebsites()
  {
    WebsiteTable::getTopRankedByUserId($this->getId());
  }
}

并在 WebsiteTable 中添加适当的查询:

class WebsiteTable extends Doctrine_Table
{
  public function getTopRankedByUserId($userId)
  {
    return Doctrine_Query::create()
     ->from('Website w')
     ->where('w.user_id = ?', array($userId))
     ->orderBy('w.nb_votes DESC')
     ->limit(5)
     ->execute();
  }
}
于 2011-01-09T18:37:23.880 回答
0

您还可以使用该getFirst()功能

$this->user->Websites->getTopRanked()->getFirst()

http://www.doctrine-project.org/api/orm/1.2/doctrine/doctrine_collection.html#getFirst ()

于 2011-03-30T17:17:07.293 回答