我试图从两个相关的模型中获取信息,显示在一个视图中。在Yii2中显示相同视图的两个模型
因此,我试图完成的是有索引视图来显示人员列表,如果我然后详细查看该特定人员,我想要一个与该人员相关的属性列表出现。
我有数据库设置,所以当我创建一个新人时,一个默认行被插入属性表中,该人员的名字叫person_id。
见我的两个模型类
人:
class People extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'people';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['dob', 'CURDATE'], 'safe'],
[['age'], 'integer'],
[['firstname', 'surname'], 'string', 'max' => 50]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'firstname' => 'Firstname',
'surname' => 'Surname',
'dob' => 'Dob',
'age' => 'Age',
'CURDATE' => 'Curdate',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getId0()
{
return $this->hasOne(Attributes::className(), ['person_id' => 'id']);
}
}
属性:
class Attributes extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'attributes';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['haircolor', 'eyecolor', 'weight', 'height', 'person_id'], 'required'],
[['weight', 'height', 'person_id'], 'integer'],
[['haircolor', 'eyecolor'], 'string', 'max' => 50]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'haircolor' => 'Haircolor',
'eyecolor' => 'Eyecolor',
'weight' => 'Weight',
'height' => 'Height',
'person_id' => 'Person ID',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPeople()
{
return $this->hasOne(People::className(), ['id' => 'person_id']);
}
}
我已经为这两个模型的生成CRUD通过GII。
我想知道的是如何设置我的人员控制器和人员查看,以便这可以正常工作。
回想一下,我的index.php视图将只显示人员列表,如果存在记录,您可以查看该特定记录,如果您查看记录 - 这将是view.php文件,我想以显示该特定人的属性(这些将是默认值),其中该人的ID与属性表中的person_id相同
然后用户将能够更新与该人有关的属性。
亲切的问候。
使用'属性'作为关系名是不可能的,并且链接教程已过时,官方文档更好http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#working -with-model-relations – soju 2015-03-19 14:31:24
谢谢。我会更新我的答案 – 2015-03-19 14:33:38