我猜你说的是GridView,如果是,那么你可以在里面有自己的专栏,没问题。就像你提到的那样,让我们将该列称为comment
如果您使用由Gii 生成的基本模板,并且您还为该模型生成了搜索类,那么您comment 可以保护属性并为该代码添加代码以便能够过滤它。
如果您可以更详细地了解所提到的列、可能的值或算法,您可能会得到更合适的答案...
也可以看看Yii 2.0: Displaying, Sorting and Filtering Model Relations on a GridView
假设您的model 称为Xyz,因为您没有提供任何信息。我还将您表中的列命名为column_from_your_table,将您的虚拟列命名为comment
在您的模型Xyz 中,您将添加关系(具有特定名称的方法来定义它)
public function getComment()
{
$column_from_your_table = $this->column_from_your_table;
$comment = '';
// your code to specify the relation
// ...
// this is value dislpayed in column grid
return $comment;
}
在文件XyzSearch.php 中\app\models\
你会有这样的东西(当然可以根据你的需要进行编辑)
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\db\Expression;
/**
* XyzSearch represents the model behind the search form about `app\models\Xyz`.
*/
class XyzSearch extends Xyz
{
public $comment; // your virtual column
/**
* @inheritdoc
*/
public function rules()
{
return [
// add it to safe attributes
[['comment'], 'safe'],
// you will have more rules for your other columns from DB probably
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = Xyz::find();
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
// I dont know your how it is your comment column autogenerated
// or what is the relation, so I give you just basic idea
// your algorythm needs to be able to be rewritten in SQL
// otherwise I dont know how you could possibly sort it
$dataProvider->sort->attributes['comment'] = [
'asc' => [Xyz::tableName().'.column_from_your_table' => SORT_ASC],
'desc' => [Xyz::tableName().'.column_from_your_table' => SORT_DESC],
'default' => SORT_ASC,
];
$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;
}
// again, you will have more filtering conditions from your generated code
// then you will add your custom filtering condition
// I dont know your how it is your comment column autogenerated
// or what is the relation, so I give you just basic idea
$query->andFilterWhere(['like', Xyz::tableName().'.column_from_your_table', $this->comment]);
return $dataProvider;
}
}
最后在您的 view 文件中添加您的虚拟列
<?php echo GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
// other columns from database
// ...
'comment',
['class' => 'yii\grid\ActionColumn'],
]
]); ?>