Yii add filter to a virtual attribute in CGridView and make it sortable

前端 未结 1 614
轻奢々
轻奢々 2020-12-31 15:18

I have the following Models :

User with columns {id,user_name,password,user_type}

Admin with columns {id,user_id,full_name,.....etc

相关标签:
1条回答
  • 2020-12-31 16:08

    What you are trying to do here is effectively add a calculated column to the result set. Imagine that in the SQL query used to fetch the results you will be joining both the Admin and Editor tables, so Admin.full_name and Editor.full_name are the two columns that will be involved in calculating the desired value.

    Since at least one Admin.full_name and Editor.full_name is always going to be NULL, the formula to calculate the final value would be

    COALESCE(Admin.full_name, Editor.full_name, '')
    

    Now that you have the calculated formula, you need to take these steps:

    1. Add a read-write column to your model to receive the calculated column
    2. Create a CDbCriteria that joins the two tables and includes the calculated column
    3. Create a CSort that describes how the calculated column should affect the record order
    4. Create a CActiveDataProvider that uses these criteria and sort options
    5. Feed the data provider to your CGridView

    So, first add a public property to the model:

    public $calculatedName;
    

    And then:

    $criteria = new CDbCriteria(array(
        'select' => array(
            '*',
            'COALESCE(Admin.full_name, Editor.full_name, \'\') AS calculatedName',
        ),
        'with'   => array('Admin', 'Editor'),
        // other options here
    ));
    
    $sort = new CSort;
    $sort->attributes = array(
        'calculatedName' => array(
            'asc'  => 'COALESCE(Admin.full_name, Editor.full_name, \'\')',
            'desc' => 'COALESCE(Admin.full_name, Editor.full_name, \'\') DESC',
        ),
        // other sort order definitions here
    );
    
    $dataProvider = new CActiveDataProvider('User', array(
        'criteria' => $criteria,
        'sort'     => $sort,
    ));
    

    And finally, use $dataProvider to populate your grid; use calculatedName as the column name.

    Apologies if I got some detail wrong, as I did not actually run this.

    Update: It turns out that Yii doesn't like it if you specify CDbCriteria.select as a string and that string contains any commas not used to separate columns (such as the commas used to separate the arguments to COALESCE). Thankfully CDbCriteria also allows passing in the columns as an array, which gets around this problem. I updated the code above to match.

    For anyone who's curious, the offending code is this.

    0 讨论(0)
提交回复
热议问题