【问题标题】:Yii2 GridView implement Filter and Sort for Values for related Table of foreign TableYii2 GridView 实现对外部表相关表的值的过滤和排序
【发布时间】:2016-02-19 16:10:50
【问题描述】:

我有 3 张桌子:

CREATE TABLE tabCve
(
    intCveID INTEGER NOT NULL AUTO_INCREMENT,
    strNumber VARCHAR(20) NOT NULL,
    fltScore FLOAT(0),
    strDescription TEXT,
    datImported DATETIME NOT NULL DEFAULT NOW(),
    intCvePhaseID INTEGER,
    intCveTypeID INTEGER,
    PRIMARY KEY (intCveID),
    KEY (intCvePhaseID),
    KEY (intCveTypeID)

) ;


CREATE TABLE tabProgress
(
    intProgressID INTEGER NOT NULL AUTO_INCREMENT,
    intProgressCveID INTEGER NOT NULL,
    intProgressUserID INTEGER NOT NULL,
    intProgressStateID INTEGER NOT NULL,
    intProgressCategoryID INTEGER,
    datCreated DATETIME NOT NULL,
    PRIMARY KEY (intProgressID),
    KEY (intProgressCategoryID),
    KEY (intProgressCveID),
    KEY (intProgressStateID),
    KEY (intProgressUserID)

) ;

CREATE TABLE tabCategory
(
    intCategoryID INTEGER NOT NULL AUTO_INCREMENT,
    strCategory VARCHAR(50) NOT NULL,
    PRIMARY KEY (intCategoryID)

) ;

我用 Gii 为 tabCve 创建了一个 CRUD。 我成功地为intCvePhaseID等引用表中的字段实现了过滤和排序功能

现在我想通过tabProgresstabCategory 实现这个 tabCvetabProgress 之间的关系是 1 比 1。

如何在我的 SearchModel 中实现它?

到目前为止我做了什么:

在模型中:

public function getProgress()
{
    return $this->hasOne(TabProgress::className(),['intProgressCveID' => 'intCveID'])->with(['category']);
}   

public function getCategory()
{
    return $this->hasOne(TabCategory::className(),['intCategoryID' => 'intProgressCategoryID']);
}

在 SearchModel 中:

公共函数搜索($params) { $query = TabCve::find();

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort'=> ['defaultOrder' => ['strNumber' => 'DESC']],
]);

$query->select(["intCveID","strNumber","fltScore","strDescription","datImported","intCvePhaseID","intCveTypeID",'progress.intProgressCategoryID']);
$query->joinWith("phase");
$query->joinWith("type");
$query->joinWith("progress");
$query->Where(['not like', 'strDescription', '** RESERVED **%', false]);
$query->andWhere(['not like', 'strDescription', '** REJECT **%', false]);
//$query->andWhere(["intProgressID" => null]);

$this->load($params);

if (!$this->validate()) {
    // uncomment the following line if you do not want to return any records when validation fails
    // $query->where('0=1');
    return $dataProvider;
}

$query->andFilterWhere([
    'intCveID' => $this->intCveID,
    'fltScore' => $this->fltScore,
    'datImported' => $this->datImported,
]);

$query->andFilterWhere(['like', 'strNumber', $this->strNumber])
    ->andFilterWhere(['like', 'strDescription', $this->strDescription])
    ->andFilterWhere(['like','tabPhase.strPhase', $this->intCvePhaseID])
    ->andFilterWhere(['like','datImported',$this->datImported])
    ->andFilterWhere(['like','tabType.strType', $this->intCveTypeID])
    ->andFilterWhere(['like','tabProgress.tabCategory.strCategory', $this->intCveTypeID])
    ;
return $dataProvider;
}

我必须如何实现这些行中的字段:

$query->select(["intCveID","strNumber","fltScore","strDescription","datImported","intCvePhaseID","intCveTypeID",'progress.intProgressCategoryID']);

和:

->andFilterWhere(['like','tabProgress.tabCategory.strCategory', $this->intCveTypeID])

【问题讨论】:

    标签: gridview yii2 crud gii


    【解决方案1】:

    在你的 seachModel 中,你需要 public var 来过滤 ..

    不需要选择,因为这是由 find.. 提供的,最好重新排列下面的代码

    $query->select(["intCveID","strNumber","fltScore","strDescription","datImported","intCvePhaseID","intCveTypeID",'progress.intProgressCategoryID']);
    $query->joinWith("phase");
    $query->joinWith("type");
    $query->joinWith("progress");
    $query->Where(['not like', 'strDescription', '** RESERVED **%', false]);
    $query->andWhere(['not like', 'strDescription', '** REJECT **%', false]);
    

    以本文档中建议的另一种方式

    http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/

    http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/

    对于

    ->andFilterWhere(['like','tabProgress.tabCategory.strCategory', 
            $this->intCveTypeID])
    

    上面链接中提供的示例建议使用 getter 来检索您需要的列,并且在 andFilterWhere 中也使用此 getter

    这样:

    在你的模型中你已经有一个

    public function getCategory()
    {
        return $this->hasOne(TabCategory::className(),
         ['intCategoryID' =>   'intProgressCategoryID']);
    }
    

    那么你可以为 strCategory 构建一个 getter

    public function getStr_category() {
        return $this->category->strCategory;
    }
    

    此时您可以使用

    检索模型搜索中的数据
    ->andFilterWhere(['like','str_category', $this->intCveTypeID])
    

    【讨论】:

    • 感谢您的反馈。我应该在这里输入什么:->andFilterWhere(['like','tabProgress.tabCategory.strCategory', $this->intCveTypeID]) 因为这种方法不起作用。
    【解决方案2】:

    访问有关此问题的完整教程:

    http://www.yiiframework.com/wiki/851/yii2-gridview-sorting-and-searching-with-a-junction-table-column-many-to-many-relationship/

    根据本教程,您应该: 1.在搜索模型中将您的相关表属性设置为公开:

    public $groupname;
    

    2 。在规则中包含属性:

        public function rules() {
            return [
                [['id', 'gender', 'status', 'sentstatus'], 'integer'],
                [['groupname', 'addeddate', 'updateddate'], 'safe'],
            ];
        }
    
    1. 在搜索模型中将默认查询更改为函数search() 中的以下代码:

      公共功能搜索($params){ $query = Contacts::find()->innerJoinWith('groups', true);
    2. 并在 andfilterwhere 中添加想要的属性。像这样:

      $query->andFilterWhere(['like', 'firstname', $this->firstname]) ... ->andFilterWhere(['like', 'groupname', $this->groupname]);

    在您的 view 类和 Gridview 中,您想要的列应该是这样的:

    'columns' => [
                    ...
                [
                    'attribute' => 'tags',
                    'format' => 'raw',
                    'value' => function ($data) {
                        $groups= '';
                        foreach ($data->groups as $group) {
                            $groups .= '<a href="/group/' . $group->id . '">' .
                            $group->group_name . '</a> | ';
                        }
                        return $groups;
             },
            'filter' => ArrayHelper::map(group::find()->asArray()->all(), 'group_name','group_name'),
                    ],
    

    如果表关系是hasOne(),你应该阅读本教程:

    http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/

    【讨论】:

    猜你喜欢
    • 2015-08-07
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多