我正在尝试使用Active Record在Yii中设置MANY_MANY关系。
我有三张桌子
简档 PROFILE_ID profile_description
类别 CATEGORY_ID CATEGORY_NAME
profile_category PROFILE_ID CATEGORY_ID
我的模型是Profile,Category和ProfileCategory。
我正在尝试使用category_id运行查询,该类别会提取该类别中的所有配置文件。
这是类别模型中的信息。
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'profiles'=>array(
self::MANY_MANY,
'Profile',
'profile_category(category_id, profile_id)',
),
'profile_category'=>array(
self::HAS_MANY,
'ProfileCategory',
'category_id',
),
);
}
个人资料模型
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'categories'=>array(
self::MANY_MANY,
'Category',
'profile_category(profile_id, category_id)'
),
'profileCategory'=>array(
self::HAS_MANY,
'ProfileCategory',
'profile_id'
),
);
}
ProfileCategory模型
public function relations()
{
return array(
'category'=>array(
self::BELONGS_TO,
'Category',
'category_id',
),
'profile'=>array(
self::BELONGS_TO,
'Profile',
'profile_id',
),
);
}
控制器
public function actionResults()
{
$category=$_POST['terms'];
$dataProvider=new CActiveDataProvider(
'Profile',
array(
'criteria'=>array(
'with'=>array('profile_category'),
'condition'=>'display=10 AND profile_category.category_id=1',
'order'=>'t.id DESC',
'together'=>true,
),
)
);
$this->render('results',array(
'dataProvider'=>$dataProvider,
));
}
查看
<div id=resultsleft>
<?php
foreach($dataProvider as $value)
{
echo $value->profile_id;
}
?>
</div>
有什么想法?谢谢!视图中没有显示任何内容。
答案 0 :(得分:2)
您必须在个人资料模型中设置名为 profileCategory 的属性(不是 profile_category ):
'profileCategory'=>array(
self::HAS_MANY,
'ProfileCategory',
'profile_id'
),
您可以将其与和条件一起使用,如下所示:
'criteria'=>array(
'with'=>array('profileCategory'),
'condition'=>'display=10 AND profileCategory.category_id=1',
'order'=>'t.id DESC',
'together'=>true,
),
答案 1 :(得分:2)
首先对逻辑id建模关系会更好......
有一个例子here。
' 个人资料 ','profile_category( profile_id ,...)'
public function relations()
{
return array(
'profiles'=>array(
self::MANY_MANY,
'Profile',
'profile_category(profile_id, category_id)'
),
'profile_category'=>array(
self::HAS_MANY,
'ProfileCategory',
'category_id',
),
);
}
' 类别 ','profile_category( category_id ,...)'
public function relations()
{
return array(
'categories'=>array(
self::MANY_MANY,
'Category',
'profile_category(category_id, profile_id)'
),
'profile_category'=>array(
self::HAS_MANY,
'ProfileCategory',
'profile_id'
),
);
}
如果数据库的模型有实际的话
很多 self :: BELONGS_TO ,数据库只有 PK(PrimaryKeys)
这样的代码将被正确执行
print_r(Profile::model()->findByPk(5)->categories);
print_r(Category::model()->findByPk(8)->profiles);