我有一个多对多的关联
articles *---* categories via article_categories
这就是article_categories的样子 编号 article_id category_id
现在我在article_categories中添加了另一列,称为"分数"
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?
}
首先,"分数"是关系的属性,而不是类别的属性。因此,您的表非常有意义,但代码需要稍微不同的方法。
定义您与类别和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;
}