how to display related data from another table?

Hi everyone.

I have two tables: "user" and "factures".

Tables schema:

USER:

id,username,password,email

FACTURES:

fid,userid,facture_name,facture_date

I used the CRUD generator and I would like to display in View all facturies which belongs to the user.

There are relationships between tables (id and userid).

How to display it in DetailView ??

Is the relationship between the 2 models already set up? I mean, does your User model have a hasMany relation named "factures" and does your Facture model has a hasOne relation named "user"?

When you have an appropriate foreign key constraint between the 2 tables, Gii should have already generated these relation methods:




/* in User model */


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getFactures()

    {

        return $this->hasMany(Facture::className(), ['userid' => 'id']);

    }


/* in Facture model */


    /**

     * @return \yii\db\ActiveQuery

     */

    public function getUser()

    {

        return $this->hasMany(User::className(), ['userid' => 'id']);

    }



If not yet, then you should write them manually, or, preferably re-run Gii’s model generator after setting up the foreign key constraint.

If yes, then you are ready to go.

You can access the facture models that belongs to a user like the following:




$user = User::find()->...->one();

foreach( $user->factures as $facture) {

    echo $facture->facture_name;

}



If you are using DetailView, something like the following will do:




    <?= DetailView::widget([

        'model' => $model, // User

        'attributes' => [

            'id',

            'username',

            'email',

            [

                'label' => 'Factures',

                'value' => function ($model) {

                    $names = [];

                    foreach( $model->factures as $facture) {

                        $names[] = $facture->facture_name;

                    }

                    return implode("<br>", $names);

                },

            ],

        ],

    ]) ?>



I used your code and I have an error:

PHP Warning – yii\base\ErrorException

htmlspecialchars() expects parameter 1 to be string, object given

Oh, I was wrong.

Try this instead:




<?php

    $names = [];

    foreach( $model->factures as $facture) {

        $names[] = $facture->facture_name;

    }

    $factureNames = implode("<br>", $names);

?>

  <?= DetailView::widget([

        'model' => $model, // User

        'attributes' => [

            'id',

            'username',

            'email',

            [

                'label' => 'Factures',

                'value' => $factureNames,

            ],

        ],

    ]) ?>



DetailView couldn’t get a closure as ‘value’ of an item. :P

I solved this problem before, but thanks a lot for your help.