おそらく私が以下に書いていることはすべて明白であり、誰もが長い間それを使用してきましたが、私は最近それを見つけ出し、思いついたので、誰かが役に立つかもしれません。
Yii2およびyii2-mongodb拡張機能は 、残念ながら、添付されたドキュメントでは機能しないため、ドキュメント指向データベースの大きな利点があります。
ドキュメントでは、添付ドキュメントに拡張機能を使用することを推奨していますが、拡張機能なしでも実行できます。
ダウンロード用のPDFファイルを生成するモデルがあり、ダウンロード数、ダウンロードされたIPアドレス、たとえばファイルがダウンロードされた時間を監視したいとします。
簡単にするために、ファイル自体は文字列に格納されていると仮定しますが、これはもちろん完全に異なる場合があります-リポジトリのどこかにあるか、関数によって形成される可能性があります。
メインモデル(一部)
/** * @property string $pdf_data , * @property array $downloads_data * */ Class PdfData extends \yii\mongodb\ActiveRecord /** @inheritdoc */ public static function collectionName() { return ['database', 'pdf'] } /** @inheritdoc */ public function attributes() { return [ 'pdf_data', 'downloads_data' ]; }
追加モデル-値をチェックして配列要素に割り当てるため
use \MongoDB\BSON\UTCDateTime /** * */ class DowmnloadData extends \yii\base\Model { /** @var \MongoDB\BSON\UTCDateTime $datetime */ public $datetime; /** @var string $clientIp */ public $clientIp; /** @var string $clientHost */ public $clientHost; /** @var string $clientUserAgent */ public $clientUserAgent; /** @var string $referer */ public $referer; /** @var bool $result */ public $result = false; /** @inheritdoc */ public function rules() { return [ ['datetime', 'default', 'value' => function() { return new UTCDateTime(strtotime("now") * 1000); }], ['clientIp', 'default', 'value' => function() { return Yii::$app->request->getUserIP(); }], ['clientHost', 'default', 'value' => function() { return Yii::$app->request->getUserHost(); }], ['clientUserAgent', 'default', 'value' => function() { return Yii::$app->request->getUserAgent(); }], ['referer', 'default', 'value' => function() { return Yii::$app->request->getReferrer(); }], ['result', 'boolean'], ]; }
さらに、ファイルを出力するコントローラーのアクションでは、次のようになります。
// -- skip -- /** * @param string $id * @return null * @throws \yii\web\NotFoundHttpException */ public function actionDownload($id) { if(($model = PdfData::findOne($id)) === null) throw new \yii\web\NotFoundHttpException(Yii::t('app', 'File not found')); $downloadData = new DowmnloadData(); if(!empty($model->pdf_data)) { $downloadData->result = true; $downloadData->validate(); // - $data = $model->downloads_data; // $data[] = $downloadData->attributes; // // array_values ( ) mongodb $model->updateAttributes(['downloads_data' => array_values($data)]); // Yii::$app->response->sendContentAsFile($model->pdf_data, 'we are the champions.pdf', [ 'mimeType' => 'text/xml', 'inline' => true ]); } return null; }
したがって、メインモデルのdownloads_data
配列内には、 DowmnloadData
でDowmnloadData
したすべての属性があり、メインモデルの属性またはデータベース内のコレクションの数を必要以上にDowmnloadData
ことなく、好きなように表示および分析できます。