【问题标题】:Doctrine : how to manipulate a collection?教义:如何操作集合?
【发布时间】:2011-06-05 22:17:41
【问题描述】:

在一个动作中使用 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();

}

【问题讨论】:

  • 你把getTopRanked()放在哪里了,看起来怎么样?
  • 查看我的编辑,我已添加该功能。 :-)
  • 您正在读取所有网站的值,而不是属于某个用户的所有网站。尽管您从用户对象中调用它,但您的查询不使用用户值...我认为 Doctrine 不会自行添加所需的 JOIN。
  • $this->user->x() 方法是您的用户模型中的方法。您将此功能放在您的 websiteTable 模型中,这是完全不同的。您应该在接受用户 ID 的网站模型中创建一个函数(例如 toprankedbyuser($user) ),或者,如果您想像上面那样访问它,请在用户模型中创建一个函数。

标签: php symfony1 doctrine doctrine-1.2


【解决方案1】:

我宁愿在方法之间传递 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
}

【讨论】:

  • 谢谢。我认为可以更改教义集合。
【解决方案2】:

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

【讨论】:

  • 那么我需要先检索别名为“网站”的用户的网站,然后再过滤它吗?
【解决方案3】:

在您的情况下 $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();
  }
}

【讨论】:

    【解决方案4】:

    你也可以使用getFirst()函数

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

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

    【讨论】:

      猜你喜欢
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多