How to make an active record behave like a CTypedList with other active records as list elements?

[center][size="5"]Link to this question on stackoverflow.com: goo.gl/a9P1r[/size][/center]

I’m just as grateful for help in this thread as for help posted on SO.com.

I found a solution. It’s called ListBehavior, an ActiveRecordBehavior that makes ARs behave like CLists. The code is based on CList, open source, and available as a gist. Feel free to use it and edit it as you like.

Example usage:


$Deck = Deck::model()->findByPk(1); // Retrieve the deck

$Card = $Deck->removeAt(0); // draw the first card (and remove it from the deck)

$Deck->shuffle(); // shuffle the deck

$n = $Deck->count(); // get the number of remaining cards in the deck

$Deck->save();



The database records will reflect the new state of the deck, including the new order of the cards and that one card has been removed from the deck.

I think this might actually be useful for some people. I’m not an experienced programmer, though, so somebody else would need to turn this into a proper extension.