2017-07-07 8 views
1

Yii2フレームワークでは、データベースから取得した既存のオブジェクトに新しい属性を動的に追加できますか?Yii2フレームワークの既存のモデルオブジェクトに新しい属性を動的に追加する

//Retrieve from $result 
$result = Result::findone(1); 
//Add dynamic attribute to the object say 'result' 
$result->attributes = array('attempt' => 1); 

それが不可能な場合は、それを実装するための別の最適な方法を提案してください。

最後に、結果をjsonオブジェクトに変換します。私のアプリケーションでは、行動のコードブロックで、私は次のように使用しています

'formats' => [ 
       'application/json' => Response::FORMAT_JSON, 
      ], 

答えて

3

あなたが連想配列のような動的属性を格納することを、あなたのモデル内のパブリック変数を定義する追加することができます。あなたはこのようにJSONを取得する結果で

public function actionJson() 
{ 
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; 

    $model = Result::findOne(1); 
    $model->dynamic = [ 
     'field1' => 'value1', 
     'field2' => 2, 
     'field3' => 3.33, 
    ]; 

    return $model; 
} 

:あなたの行動..in

class Result extends \yii\db\ActiveRecord implements Arrayable 
{ 
    public $dynamic; 

    // Implementation of Arrayable fields() method, for JSON 
    public function fields() 
    { 
     return [ 
      'id' => 'id', 
      'created_at' => 'created_at', 
      // other attributes... 
      'dynamic' => 'dynamic', 
     ]; 
    } 
    ... 

は、あなたのモデルにいくつかの動的な値を渡すと、JSON、すべてを返します。それはこのような何かを見てみましょう:

{"id":1,"created_at":1499497557,"dynamic":{"field1":"value1","field2":2,"field3":3.33}} 
+0

これは機能しています。モデルクラスのフィールド宣言なしで行うことは可能ですか? –

+0

残念ながら、ActiveRecordを使用する場合は不可能です。 –

関連する問題