Sunday, February 28, 2010

AppModel schizophrenia

I have several models for which I want to list the latest entries in a
sidebar. All models have a title & slug, so to keep from repeating
code, I've put the method in AppModel.

AppModel:

public function getLatest($limit = 10)
{
$filters = array(
'limit' => $limit,
'order' => $this->alias . '.created DESC',
'fields' => array(
$this->alias . '.id',
$this->alias . '.created',
$this->alias . '.title',
$this->alias . '.slug'
),
'recursive' => -1
);

return $this->find('all', $filters);
}


default layout:

echo $this->element('news_items/latest', array('cache'=>'1 day'));
echo $this->element('posts/latest', array('cache'=>'1 day'));
echo $this->element('galleries/latest', array('cache'=>'1 day'));

views/elements/galleries/latest.ctp:

$latest_galleries = $this->requestAction('/galleries/getlatest/5');
...

PostsController:

public function getLatest($limit)
{
return $this->Post->getLatest($limit);
}

GalleriesController:

public function getLatest($limit)
{
return $this->Gallery->getLatest($limit);
}

(caching is disabled, btw, and everything has been deleted from tmp/
cache, anyway)

This works just fine except that the find() for Gallery is always
selecting from the posts table!

SELECT `Gallery`.`id`, `Gallery`.`created`, `Gallery`.`title`,
`Gallery`.`slug`
FROM `posts` AS `Gallery`
WHERE 1 = 1 ORDER BY `Gallery`.`created` DESC LIMIT 5


There's absolutely nothing in Gallery model that mentions Post. When I
save a Gallery, it's saved to the galleries table. Likewise, fetching
for the index or view actions is all correct. The problem only shows
up with these elements. And, if I re-order the elements in any way, I
get the same result--always the Gallery results are fetched from the
posts table.

If I remove the call to the posts element from the layout, the
galleries element is still wrong.

And notice that $this->alias is correct--'Gallery'--but the table is
wrong.

I've checked that the requestAction() does correctly call the
GalleriesController. The trouble seems to be with the model.

Ring any bells?

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: