Tuesday, March 8, 2022

[FIXED] YII: How to use "with" and sort at the same time?

Issue

I've got a problem on YII relation tables.

As the title says, I just want to combine table "A" with table "B" and sort the combined table according to the "clickTimes" in table "B".

        $A = self::find()
        -> with(['B'=>['order'=>'clickTimes DESC']])
        -> all();

The above is what I've learned from the Internet but it didn't work. The error goes below.

PHP Warning – yii\base\ErrorException
call_user_func() expects parameter 1 to be a valid callback, array must have exactly two members

The relation works fine except for the sorting. Any suggestion? Thank you so much!


Solution

You may use CDbCriteria like this:

$criteria = new CDbCriteria();
$criteria->with = array('foreign_table1', 'foreign_table2',  'foreign_table2.foreign_table3');
$criteria->order = 'foreign_table3.col5 DESC';


Answered By - Jobayer Ahmed

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.