开发者

symfony/doctrine special query (MAX) with Doctrine_Query::create()

I am trying to add a new query to my app and I'm stuck a bit. I also don't really know what to use as search term, so I'm stuck.

Ok, let's get into it right now:

Table: a
primary key: id
string: name

Table: b
primary key: id
foreign key: a_id
int: cluster

What I want to do is retrieve the max cluster int for a given object a. In SQL:

SELECT MAX(b.cluster) FROM b WHERE b.a_id = ? GROUP BY b.cluster;

As I'm using symfony 1.4 and doctrine 1.2, I want to get it right by adding a method to Class a with the name maxCluster():

class A extends BaseA{

  ..

  public function maxCluster(){
    $q = Doctrine_Query::create()->select('MAX(b.cluster)')->from('B b')->where('b.a_id = ?', $this->getId())->groupBy('b.cluster');
    return Doctrine_Core::getTable('A')->execute($q);
  }
}

When doing this, I get the following error message:

A query with the name A/SELECT MAX(b.cluster) FROM B b WHERE b.a_id = ? GROUP BY b.cluster does not exist.

I think the solution should be not that complicated, I'm just stuck right now.

Thanks for any help, Sebastian

E开发者_如何转开发DIT: I got a hint, so know the code of the maxCluster-function looks like this:

$q = Doctrine_Query::create()->select('MAX(b.cluster) AS maxCluster')->from('B b')->where('b.a_id = ?', $this->getId())->;
$result = $q->fetchOne();
return $result->maxCluster;

The question for me right now is: Is this the best way? I'm confused that fetchOne returns a picture-array. I wouldn't expect such a behaviour because I select one int and not objects. Maybe anyone can point out what best pratice for such queries is.


The execute methon relative to getTable is used to execute named queries, have a look at the doctrine manual to find more if you want to use them.

Or you can use return $q->execute() to return the result of the query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜