简体   繁体   中英

How to get data from model A in view B Yii2

I am quite new to Yii 2 and I am currently trying to display data from the Teams model in the User view in a GridView . In Yii1 I used a function with the $data variable. In Yii2 it does not seem to work that way.

I have tried the following in the /user/index.php

<?php

use yii\helpers\Html;
use yii\grid\GridView;

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'Users');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="user-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a(Yii::t('app', 'Create User'), ['create'], ['class' => 'btn btn-success']) ?>
    </p>


    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            // ['class' => 'yii\grid\SerialColumn'],
            // 'iduser',
            'username',
            'surname',
            'givenname',
            'email:email',
            'mobile',
            'admin:boolean',
            'language',
            // Below is what I have been trying to do so far...
            ['class' => 'yii\grid\DataColumn',
             'label' => 'Teams',
             'value' => 'getTeams($data-teams)'
            ],
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


</div>

<?php
// And this is the function I use. In Yii1 it worked just fine.
function getTeams($data) {
    $tmp = "";foreach ($data as $team) {
      $tmp .=$team['name'].", ";
    }
    return trim($tmp, ", ");
  }
?>

I have been looking around but can't seem to find a solution for this one. Basically I simply want the Team to be displayed in which the user is a part of. There is a table called UserHasTeam in which the id's of the teams and users are saved.

I am a little lost on how to go about the entire thing. Any help is greatly appreciated.

I assume you have properly set relation to Team model in User model. See the Relations via Junction Table part of guide if you don't know how to set the relation.

You can use closure in $value property of DataColumn to control what value is used for column.

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'columns' => [
        // ... other columns ...
        [
            'label' => 'Teams',
            'value' => function($model) {
                $tmp = "";
                foreach ($model->teams as $team) {
                    $tmp .= $team->name .", ";
                }
                return trim($tmp, ", ");
            }
        ],
    ],
]); ?>

You might also want to consider using eager loading to load all related at once instead of running query for each user in grid.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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