2

I have a News model, which has a HABTM relationship with an Artists model, and an artist in turn hasMany tourdates.

If I want to find all tourdates related to the current news item, what is an efficient way of phrasing that for CakePHP?

This is what I have so far; I'm wondering if (a) it looks like it should work, and (b) if there's any more concise way of writing it:

    $relatedartists = $this->News->ArtistsNews->find('list', array(
        'conditions'=>array('ArtistsNews.news_id' => $id),
        'fields'=>array('artist_id')
    ));
    $livedates = $this->News->Artists->Tour->find('all', array(
        'conditions'=>array('Tour.artist_id'=> $relatedartists, 
            'date >= ' . time()),
        'order'=>'date ASC'
    ));
thesunneversets
  • 2,560
  • 3
  • 28
  • 46

1 Answers1

0

What you have is pretty good. I always prefer to use multiple queries rather than use massive joins which create temporary tables. It can reduce performance somewhat.

You might also try something like the below

$opts = array(
  'conditions' => array(
     'ArtistsNews.news_id' => $id
   )
);
$this->News->Artists->recursive = 2;
$this->News->Artists->find('all', $opts);

Something along the likes of this query will also get you what you need (haven't error checked)

JohnP
  • 49,507
  • 13
  • 108
  • 140
  • 1
    recursive 2 is never a good option. leads to pulling everything from the db. Containable is the way to do it. – dogmatic69 Mar 30 '11 at 12:26
  • I did point out that what the OP has is a good setup. I'm well aware of Containable and only offered this as an alternative because the OP wants to pull all data. – JohnP Mar 30 '11 at 12:40
  • Mm, yeah, I fear recursive. I have started using Containable for various things but maybe haven't yet grasped the full possibilities for what it can do. Maybe I need to read through that section of the Cookbook once again... – thesunneversets Mar 30 '11 at 19:42