doupeizheng3918 2017-03-01 18:46
浏览 79
已采纳

Yii2在gridview中获取多对多关系的数据并应用过滤器

i'm developing a web application with Yii2 framework, and i'm facing a problem right now. I want to display the data from a many-to-many relation in a gridview and be able to filter from those fields later on.

I've read the official documentation here, some stackoverflow post like this and other resources but can't seem to get it to work. I have 3 tables: actividad, plan_actividad and circulo_icare, actividad is related to plan_actividad and circulo_icare is also related to it (plan_actividad is the junction table). So i have defined the following relations in my Actividad model:

class Actividad extends \yii\db\ActiveRecord 
{
   .... 

public function getPlanActividad()
{
    return $this->hasMany(PlanActividad::classname(), ['act_id' => 'act_id']);
}

public function getCirculo()
{
    return $this->hasMany(CirculoIcare::classname(), ['cirica_id' => 'act_id'])->via('planActividad');
}

...
}

The in my view index.php i'm trying to show the values in a gridview like this:

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

        // 'act_id',
        ['attribute' => 'Codigo Evento', 'value' => 'act_numorden'],
        ['attribute' => 'Nombre Evento', 'value' => 'act_nombre'],
        ['attribute' => 'Fecha Evento', 'value' => 'act_fecha'],
        ['attribute' => 'Locacion', 'value' => 'locacion.loc_nombre'],
        [
        'attribute' => 'Circulo',
        'value' => 'circulo.cirica_nombre',

        ],
        ['attribute' => 'Circulo id',
         'value' => 'planActividad.cirica_id',
        ],
        // 'act_horaini',
        // 'act_horafin',
        // 'act_idencuesta',
        // 'act_vigencia:boolean',
        // 'loc_id',

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

The problem is, i can't get any values to show with the circulo relation, it always shows (not set). If i change hasMany in getPlanActividad() with hasOne() then it shows some values (only 2 of 11 it should, based on the cirica_id that exist on plan_actividad table) but these are not correct anyway. I know that i can filter for those fields later on in search view but i don't really understand why the relations doesn't work as i expected.

Any help would be greatly appreciated, let me know if more info is needed and thank you in advance.

  • 写回答

1条回答 默认 最新

  • douchun1900 2017-03-09 16:48
    关注

    Answering my own question (credits to softark from the yii official forums).

    In order for the relation to work as expected, I had to change:

    public function getCirculos()
    {
         return $this->hasMany(CirculoIcare::classname(), ['cirica_id' => 'act_id'])->via('planActividad');
    }
    

    to

    public function getCirculos()
    {
         return $this->hasMany(CirculoIcare::classname(), ['cirica_id' => 'cirica_id'])->via('planActividad');
    }
    

    and use a callback function in the gridview to display the correct values, since a hasMany relation gives an array of models and not a single model. So I modified the gridview code to:

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        // 'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
    
            ...
    
            ['attribute' => 'circulo',
             'value' => function($model){
                $items = [];
                foreach($model->circulos as $circulo){
                    $items[] = $circulo->cirica_nombre;
                }
                return implode(', ', $items);
             }],
    
            ...
    
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
    

    This gives the expected results. You can then apply filter by the relation fields easily by adapting the search model.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?