yii活动记录连接模型

时间:2012-08-09 07:41:15

标签: activerecord join yii

使用Yii框架。

我有3个模特。

文章 - 表格文章(id,name)

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

作者 - 表作者(id,name)

我需要获取作者。*,article_to_authors.type用于特定的article_id。

我试图在ArticlesToAuthors模型中建立关系:

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

然后我提出了查询:

$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. 我可以将所有活动记录对象合并到一起,而不是在foreach中做foreach吗? 我需要一个模拟sql“SELECT atoa。,a。 FROM articles_to_authors atoa LEFT JOIN作者ON atoa.author_id = a.id WHERE atoa.article_id =:article_id”

  2. 我做对了吗?

  3. P.S。 - 抱歉我的英语不好。

1 个答案:

答案 0 :(得分:1)

看起来您需要以下关系:

ArticlesToAuthors表中:

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

并且,为了完整起见,请在Authors表中填写:

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

允许您访问$a->author->name。没有经过测试,这只是我的头脑。

相关问题