如何访问关联表中的列?

时间:2013-11-06 02:56:28

标签: php activerecord phpactiverecord

我有多对多的关联

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?
 }

1 个答案:

答案 0 :(得分: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;
}