学说:如何操纵集合?

时间:2011-01-08 23:43:24

标签: php symfony1 doctrine doctrine-1.2

使用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 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:1)

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

访问它

答案 2 :(得分:1)

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

我只是在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();
  }
}

答案 3 :(得分:0)

您还可以使用getFirst()功能

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

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