0

我有一个多对多关联

articles *---* categories via article_categories

这就是 article_categories 的样子 id article_id category_id

现在,我在 article_categories 中添加了另一个名为“score”的列

  id
  article_id
  category_id
  score

这是我写出类别的方式

 foreach ($article->categories as $c) {
      echo $c->title     
 }

我想在类别标题旁边输出 article_category 分数。我怎么做?

但我还需要输出分数和标题

 foreach ($article->categories as $c) {
      echo $c->title
      echo $c->  ?     # how do I do this here?
 }
4

1 回答 1

1

首先,“分数”是关系的属性,而不是类别的属性。所以你的表格很有意义,但代码需要稍微不同的方法。

定义您与类别和 article_categories 的关系,例如:

Article extends ActiveRecord\Model {
    static $has_many = array(
        array('article_categories', 'class_name'=>'ArticleCategory') // php-AR's pluralization won't work by default
        array('categories', 'through' => 'article_categories'),
    );
}

ArticleCategory extends ActiveRecord\Model {
    static $belongs_to = array(
        array('article'),
        array('category'),
    );
}

// So for simple and direct access to the category and its attributes you can do:
foreach ($article->categories as $c) {
    echo $c->title;
}
// To also get the score you have to: 
foreach ($article->article_categories as $ac) {
    echo $ac->category->title;
    echo $ac->score;
}
于 2013-11-06T20:56:21.357 回答