Define a custom order in the relations () method in Yii

I have a model A that has a relationship of type HAS_MANY to model B. B:

id, user_id, message, date, parent_message_id 

I need the elements of model B to be ordered by date (descending), but if parent_message_id is different from zero, then the date to be taken into account should be the date corresponding to parent_message_id.

Can I customize the criteria used to streamline the relationship? Does anyone know how I could do this?

+7
source share
2 answers

Ok, I solved it like this: model A HAS_MANY model B, so I redefined the relationship method to the following:

 public function relations() { return array( 'messages' => array(self::HAS_MANY, 'WallMessages', 'liga_id', 'condition'=>'specific_post.parent_message_id IS NULL', 'order'=>'specific_post.date DESC', 'alias'=>'specific_post'), ); } 

Therefore, I only compare the date of these messages without a parent identifier. The disadvantage is that I have to access each message "child messages" ... but well, I could not find another workaround. Thank you all for your help!

+10
source

I think that only sorting items is possible only in the same column. However, there may be a ninja database that could help you.

In an ideal world, you can use the afterFind () method for any setting at any level, not only for sorting, but also for changing some values ​​for others. It may not be as fast as a planned order, but in this way you free the MySQL server from a small load. Plus it is called automatically. Greetings

0
source

All Articles