У меня реализовано поведение HistoryBehavior, которое отвечает за сохранение истории создания/редактирования моделей в коллекцию histrory (mongodb).
Код: Выделить всё
class HistoryBehavior extends Behavior
{
const COLLECTION_NAME = 'history';
/**
* @var \yii\mongodb\Collection
*/
private $collection;
/**
* @var \app\models\mongo\History
*/
public $history;
public function init()
{
parent::init();
$this->collection = Yii::$app->mongodb->getCollection(self::COLLECTION_NAME);
}
public function events()
{
return [
ActiveRecord::EVENT_AFTER_INSERT => 'addCreateInformation',
ActiveRecord::EVENT_BEFORE_UPDATE => 'addUpdateInformation',
ActiveRecord::EVENT_AFTER_FIND => 'initHistory',
];
}
/**
* Добавление информации о создании
* @return boolean
*/
public function addCreateInformation($event)
{
...
}
/**
* Добавление информации о редактировании
* @return boolean
*/
public function addUpdateInformation($event)
{
...
}
/**
* Инициализация атрибута $history
* @return boolean
*/
public function initHistory($event)
{
$this->history = History::findOne($this->owner->_id);
return true;
}
}
Код: Выделить всё
public function afterFind()
{
// convert \MongoDB\BSON\UTCDateTime to string date format 'd.m.Y'
$this->pass_date = date('d.m.Y', $this->pass_date->toDateTime()->getTimestamp());
$this->date_start = date('d.m.Y', $this->date_start->toDateTime()->getTimestamp());
$this->date_end = date('d.m.Y', $this->date_end->toDateTime()->getTimestamp());
$this->department_id = $this->department_id['$id'];
$this->shelf_life_id = $this->shelf_life_id['$id'];
// set values for location object
$this->location = new Location(
$this->location['place']['$id'], $this->location['rack']['$id'],
$this->location['shelf']['$id'], $this->location['shelf_place']
);
$this->tomes = $this->getTomesModels();
}