在Yii中如何显示两个表的数据
我有两张桌子在Yii中如何显示两个表的数据,yii,Yii,我有两张桌子 User --------- id username password level company_id Company ----------- id name website 现在我想显示用户列表(Gridview)及其公司名称,其中company_id=1您必须在模型中使用关系。通过gii创建模型后,转到用户模型并更改关系方法,如下所示: public function relations() { return array( 'company'=&
User
---------
id
username
password
level
company_id
Company
-----------
id
name
website
现在我想显示用户列表(Gridview)及其公司名称,其中company_id=1您必须在模型中使用关系。通过
gii
创建模型后,转到用户
模型并更改关系
方法,如下所示:
public function relations() {
return array(
'company'=>array(self::HAS_ONE,'Company','company_id')
);
}
$user=User::model()->findByPk(10); //for example user with id=10
echo $user->company->name; //it returns the relative company name
然后,您可以执行以下操作:
public function relations() {
return array(
'company'=>array(self::HAS_ONE,'Company','company_id')
);
}
$user=User::model()->findByPk(10); //for example user with id=10
echo $user->company->name; //it returns the relative company name
注意事项:
- 我假设每个用户都有一个公司。这就是为什么我写了
self::HAS_ONE
- 在
中,您可以执行以下操作:CGridView
$data->company->name
只是关系的名称,而company
是相关模型company
- Yii有一个强大而全面的文档。所以,最好看一下它的官方文件李>