user1586760
user1586760

Reputation: 33

yii active record join models

Using Yii framework.

I have 3 models.

Articles - table articles(id, name)

ArticlesToAuthors - table articles_to_authors (id, article_id, author_id, type)

Authors - table authors (id, name)

I need to get authors.*, article_to_authors.type for specific article_id.

I was trying to make relation in ArticlesToAuthors model like that:

'authors'  => array(self::HAS_MANY, 'Authors', array('id' => 'author_id'), ),

then i made query:

$authors = ArticlesToAuthors::model()->with('authors')->findAll(array('condition' => 'article_id=2217') );


foreach($authors as $a)
{
     //this is not working
     #var_dump($a->authors->name);
         #var_dump($a->name);

     //this works fine
     foreach($a->authors as $aa)
     {
            var_dump($aa->name);
     }
}
  1. Can i get all active record object in one and not to do foreach in foreach? I need an analogue to sql "SELECT atoa., a. FROM articles_to_authors atoa LEFT JOIN authors a ON atoa.author_id=a.id WHERE atoa.article_id=:article_id"

  2. Am i doing right?

p.s. - sorry for my bad english.

Upvotes: 3

Views: 2514

Answers (1)

Stu
Stu

Reputation: 4150

It looks like you need the following relations:

in your ArticlesToAuthors table:

'author' => array(self::BELONGS_TO, 'Authors', 'author_id'),
'article' => array(self::BELONGS_TO, 'Articles', 'article_id'),

and, for completeness, in your Authors table:

'articlesToAuthors'  => array(self::HAS_MANY, 'ArticlesToAuthors', array('id' => 'author_id'), ),

This should allow you to access $a->author->name. Not tested, that's just off the top of my head.

Upvotes: 1

Related Questions