在 yii 中对自定义列 Fullname 应用排序和搜索

Applying sorting and searching on a custom column Fullname in yii

我有一个 tbl 人有 id,first_name,last_name.Now 在 YII 中使用 getter 我创建了一个显示 first_name+[=22= 的函数 getFullName ..它工作正常,但它在没有排序选项的情况下显示全名列,默认情况下 first_name 和 last_name 有它。 我没有任何 YII 经验 before.How 全名列可以排序吗?? 谢谢

型号:人

namespace app\models;

use Yii;

/**
 * This is the model class for table "person".
 *
 * @property integer $id
 * @property string $first_name
 * @property string $last_name

 */
class Person extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'person';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['first_name', 'last_name'], 'required'],
            [['first_name', 'last_name'], 'string', 'max' => 100],
            [['fullName'], 'safe']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'first_name' => Yii::t('app', 'First Name'),
            'last_name' => Yii::t('app', 'Last Name'),
            'fullName' => Yii::t('app', 'Full Name')

        ];
    }

   public function getFullName()
   {
      return $this->first_name . " " . $this->last_name;
   }

}

查看Person:index.php

    <?php

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

/* @var $this yii\web\View */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = Yii::t('app', 'People');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="person-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <p>
        <?= Html::a(Yii::t('app', 'Create Person'), ['create'], ['class' => 'btn btn-success']) ?>
    </p>

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

            'id',
            'first_name',
            'last_name',
            'fullName',

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

</div>

1) 模型中的 Delcare public $fullname; class 人

2) 在你的 Person 模型中 class search method 添加以下行(我使用了 yii 语法,请将其转换为 yii2 语法),

    $criteria=new CDbCriteria;
    $criteria->select = " *, CONCAT_WS(' ', first_name, last_name) as fullname";
    $criteria->compare('fullName',$this->fullName);
    ..........
   // your compare code goes here
    ......... 
    $sort = new CSort();
    $sort->attributes = array(
        'fullName'=>array(
            'asc'=>'fullName ASC',
            'desc'=>'fullName DESC',
        ),
        '*', 
    );

    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
        'sort'=>$sort,
    ));