Wednesday, December 30, 2009

Re: Count column in index view

Hi Jeremy,

Seems like Contain can't find out to make a join when there is a
hasMany relationship between the Author and the Article models. I made
changes to Example A, so that Contain makes a LEFT JOIN, which
includes Authors with no Articles :)

1) Unbind the hasMany relationship.
2) Bind a hasOne relationship.
3) Make the find on the Author model - I have include two author ids
with articles and one (13) without articles.
[code]
$this->Article->Author->unbindModel( array('hasMany' => array
('Article')));
$this->Article->Author->bindModel( array('hasOne' => array
('Article')));
$results = $this->Article->Author->find(
'all',
array(
'contain' => array('Article'),
'fields' => array('Author.id', 'Author.name', 'COUNT
(Article.id) as article_count'),
'conditions' => array('Author.id' => array(1,2,13)),
'group' => array('Author.id', 'Author.name'),
)
);
debug($results);
[/code]

The result is:
[result]
28871\controllers\articles_controller.php (line 48)
Array
(
[0] => Array
(
[Author] => Array
(
[id] => 1
[name] => Hans Christian Andersen
)
[0] => Array
(
[article_count] => 19
)
)
[1] => Array
(
[Author] => Array
(
[id] => 2
[name] => Terry Prattchet
)
[0] => Array
(
[article_count] => 19
)
)
[2] => Array
(
[Author] => Array
(
[id] => 13
[name] => Test
)
[0] => Array
(
[article_count] => 0
)
)
)
[/result]

Hope this helps you on the way,
John


On Dec 30, 6:52 am, Jeremy Burns <jeremybu...@me.com> wrote:
> Thanks John. Option B does indeed work - sort of! It returns a list of
> location types with a count of their locations, but only where there
> is a location. In other words, it does not give me the location types
> that do not have have any locations.
>
> Any more ideas - anyone?
>
> On Dec 29, 12:35 pm, John Andersen <j.andersen...@gmail.com> wrote:
>
> > A correction, example A gives the author with all the articles, but
> > the article count is 1 (one) - so no luck using that!
> > Enjoy,
> >    John
> > [snip]

Check out the new CakePHP Questions site http://cakeqs.org and help others with their CakePHP related questions.

You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php?hl=en

No comments: