如何将关系属性添加到 gridview yii2?

how to add relational attributes to gridview yii2?

我有一个新问题yii2。 如何在 views/viewname/index 的 gridview 中显示其他表的关系值,并向其添加确认按钮?

谢谢

<?php

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

/* @var $this yii\web\View */
/* @var $searchModel app\models\LaptopSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Laptops';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="laptop-index">

    <h1><?= Html::encode($this->title) ?></h1>
    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

    <p>
        <?= Html::a('Create Laptop', ['create'], ['class' => 'btn btn-success']) ?>
    </p>
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            'id',
            'network',
            'technology',
            'sup_id',
            'speaker',
            // 'optical_drive',
            // 'webcam',
            // 'touchpad',
            // 'card_reader',
            // 'ethernet',
            // 'vga',
            // 'hdmi',
            // 'usb3_ports',
            // 'usb2_ports',
            // 'usb_type_c',
            // 'thunderbolt_ports',
            // 'serial_ports',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>

如何在此处添加新属性并添加按钮?

获取可以添加到模型中的相关值

关系函数

public function getYourRelatedModel()
{
    return $this->hasOne(YourRelatedModel::className(), ['id' => 'your_id_fk']);
}

并为您需要的字段添加 getter

public function getYour_field() {
    return $this->yourRelatedModel->your_field;
}

最后将列

添加到您的 gridview
'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'id',
        'network',
        'technology',
        'sup_id',
        'speaker',
        'your_field',

how to show relational values from other tables in gridview

考虑订单和客户模型

为了模型建立客户关系。

public function getCustomer()
{
    return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
}

在订单列表页面显示客户名称

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            [
              'label' => 'Customer',
              'attribute' => 'customer_id',
              'value' => function($data) {
                   return $data->customer->name;
               },
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

is there any way to make sortby link for that?

将 "attribute" 添加到网格列,它解决了可排序问题

        [
            'value'=> 'customer.name',
            'label' => 'Customer Name',
        ],

试试这个来显示客户姓名!

如果你想对此进行排序,你需要在 searchModel 中创建一个 customerName 假属性并使用它。