简体   繁体   English

Yii2中显示相同视图的两个模型

[英]Two Models Displaying to Same View in Yii2

I am trying to get information from two models that are related, displayed in one view. 我正在尝试从一个视图中显示的两个相关模型中获取信息。

So what I am trying to accomplish is have the index view to show the list of people, if I then go into detail view of that particular person I want a list of attributes relevant to that person to appear. 因此,我要完成的工作是使索引视图显示人员列表,如果接下来进入该特定人员的详细视图,我希望显示与该人员相关的属性列表。

I have the database setup so that when I create a new person a default row gets inserted into the attributes table with the id of the person under the column called person_id. 我有数据库设置,以便在创建新人员时将默认行插入到属性表中,其中该人员的ID在名为person_id的列下。

See my two model classes 看我的两个模型课

People: 人:

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']);
    }
}

Attributes: 属性:

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']);
    }
}

I have generated CRUD through Gii for both of these models. 我已经通过Gii为这两种模型生成了CRUD。

What I would like to know is how to setup my people controller and people view so that this may work properly. 我想知道的是如何设置我的人员控制器和人员视图,以便它可以正常工作。

Just to recap, my index.php view will just show the list of people, if a record exists, you can view that specific record, if you view the record - which will be the view.php file, I want to show the attributes(These will be the default values) of that particular person where the id of the person is the same as the person_id in the attributes table 回顾一下,我的index.php视图将仅显示人员列表,如果存在记录,则可以查看该特定记录,如果您查看该记录-这将是view.php文件,我想显示属性该特定人员的ID(这些值为默认值),该人员的ID与属性表中的person_id相同

The user will then be able to update the attributes relating to that person. 然后,用户将能够更新与该人有关的属性。

Kind Regards. 亲切的问候。

Here an example : 这是一个例子:

public function actionCreate()
{   
    $user = new User;
    $profile = new Profile;

    if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post()) && Model::validateMultiple([$user, $profile])) {

        $user->save(false); // skip validation as model is already validated
        $profile->user_id = $user->id; // no need for validation rule on user_id as you set it yourself
        $profile-save(false); 

        return $this->redirect(['view', 'id' => $user->id]);
    } else {
        return $this->render('create', [
            'user' => $user,
            'profile' => $profile,
        ]);
    }
}

More informations : 更多信息:

http://www.yiiframework.com/forum/index.php/topic/53935-solved-subforms/page__p__248184 http://www.yiiframework.com/forum/index.php/topic/53935-solved-subforms/page__p__248184

http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html

To display related information in a view, you get the best performance with eager loading. 要在视图中显示相关信息,急切加载将获得最佳性能。 I'll provide an example: 我将提供一个示例:

public function actionView($id)
{
    $model = Person::find()
        ->where(['id' => $id])
        ->with('id0')
        ->one();

    return $this->render('view', [
            'model' => $model,
    ]);
}

Now i see that your relation in Person Model is called getId0, you can for readability change that to getAttribs(), and change to ->with('attribs') but that is just a digression :) 现在,我看到您在Person Model中的关系称为getId0,您可以将可读性更改为getAttribs(),然后更改为->with('attribs')但这只是题外话:)

EDIT: as @soju commented, attributes is not possible to use as a relation name, and that is why gii has given it the name getId0. 编辑: 正如@soju所评论的那样,属性不能用作关系名称,这就是为什么gii给它指定了名称getId0。 Attribs or something more informative can be helpful on readability. 属性或更多有用的信息可能有助于提高可读性。

If you want to show the results in a widget, like GridView or ListView, you can follow the guide here: 如果要在GridView或ListView之类的小部件中显示结果,则可以按照以下指南进行操作:

http://www.ramirezcobos.com/2014/04/16/displaying-sorting-and-filtering-model-relations-on-a-gridview-yii2/ http://www.ramirezcobos.com/2014/04/16/displaying-sorting-and-filtering-model-relations-on-a-gridview-yii2/

EDIT2: as @soju commented, guide is possibly outdated. EDIT2: 正如@soju所说,指南可能已过时。 Read official documents aswell. 还要阅读官方文件。 http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#working-with-model-relations http://www.yiiframework.com/doc-2.0/guide-output-data-widgets.html#working-with-model-relations

If you want to create your own view, you can access the values with $model->id0->haircolor or, if you rename the relation, $model->attribs->haircolor just like you would any other attribute. 如果要创建自己的视图,则可以使用$model->id0->haircolor来访问值,或者,如果重命名关系, $model->attribs->haircolor可以像其他任何属性一样$model->attribs->haircolor

Remember: using GridView / ListView requires the table name from the db when displaying, like 'attributes.eyecolor' , but the $model->id0 requires the relation name from the model, without the 'get' in front, and with lower case. 记住:使用GridView / ListView在显示时需要数据库中的表名,例如'attributes.eyecolor' ,但是$model->id0需要$model->id0的关系名,前面没有'get'并且小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM