【问题标题】:Yii2: has_many gridview and detailviewYii2: has_many gridview 和 detailview
【发布时间】:2016-05-05 01:25:13
【问题描述】:

我将在我的 Yii2 项目中使用第一种规范化形式,所以我添加了这样的表格
|编号 | post_id | tag_id |
当我要发布模型时,我写了这个:

public function getTags()
{
    return $this->hasMany(PostTags::className(), ['post_id' => 'id']);
}

在视图小部件中,我添加了“tags.tag_id”,但它没有显示任何数据。
有没有办法在 DetailViewGridView 小部件中显示此标签?

也许,我可以在某处写“group_concat”?

【问题讨论】:

  • 我找到了问题所在。我没有将 joinWith 添加到 DataProvider 查询

标签: php yii2


【解决方案1】:

我建议编写一个小部件来显示相关记录的链接列表。它是可重用的,防止在模型/控制器中生成 HTML,减少视图中的代码量。

<?php

namespace common\widgets;

use yii\base\Widget;
use yii\helpers\Html;

/**
 * Widget for display list of links to related models
 */
class RelatedList extends Widget
{
    /**
     * @var \yii\db\ActiveRecord[] Related models
     */
    public $models = [];

    /**
     * @var string Base to build text content of the link.
     * You should specify attribute name. In case of dynamic generation ('getFullName()') you should specify just 'fullName'.
     */
    public $linkContentBase = 'name';

    /**
     * @var string Route to build url to related model
     */
    public $viewRoute;

    /**
     * @inheritdoc
     */
    public function run()
    {
        if (!$this->models) {
            return null;
        }

        $items = [];
        foreach ($this->models as $model) {
            $items[] = Html::a($model->{$this->linkContentBase}, [$this->viewRoute, 'id' => $model->id]);
        }

        return Html::ul($items, [
            'class' => 'list-unstyled',
            'encode' => false,
        ]);
    }
}

以下是一些示例(假设标签名称存储在name 列中)。

GridView中的用法:

[
    'attribute' => 'tags',
    'format' => 'raw',
    'value' => function ($model) {
        /* @var $model common\models\Post */
        return RelatedList::widget([
            'models' => $model->tags,
            'viewRoute' => '/tags/view',
        ]);
    },
],

DetailView中的用法:

/* @var $model common\models\Post */

...

[
    'attribute' => 'tags',
    'format' => 'raw',
    'value' => RelatedList::widget([
        'models' => $model->tags,
        'viewRoute' => '/tags/view',
    ]),        
],

不要忘记设置格式raw,因为默认情况下内容呈现为纯文本以防止XSS攻击(html特殊字符被转义)。

您可以修改它以满足您的需要,这只是一个示例。

【讨论】:

  • 问题是我需要像“tags.id”这样的东西。当我使用 hasOne 关系时,我只需要写“tags.id”,它只显示第一个选定的元素,但如果我使用多个 id,它就不起作用
猜你喜欢
  • 1970-01-01
  • 2015-08-11
  • 2016-07-13
  • 1970-01-01
  • 2016-03-24
  • 2015-11-19
  • 2017-03-26
  • 2017-07-10
  • 2017-05-17
相关资源
最近更新 更多