将yii2中的相关属性传递给json输出

时间:2017-01-26 10:51:13

标签: php json yii2

将数据返回到rest api并且我想返回两个属性和相关属性

这就是我所拥有的

$query = User::find()->joinWith('role');

当我表演时

var_dump($query->all())

我得到一个表格数组(属性和相关属性)

  [1]=>
 object(common\models\User)#119 (10) {
  ["_attributes":"yii\db\BaseActiveRecord":private]=>
array(18) {
  ["id"]=>
  int(27)
  ["username"]=>
  string(8) "marshal2"
  ["email"]=>
  string(18) "marshal2@gmail.com"
 }

["_related":"yii\db\BaseActiveRecord":private]=>
array(1) {
  ["role"]=>
  object(common\rbac\models\Role)#131 (8) {
    ["_attributes":"yii\db\BaseActiveRecord":private]=>
    array(3) {
      ["item_name"]=>
      string(23) "Tracking center officer"
      ["user_id"]=>
      int(27)

    }

  }
}

}   ...

通过

将结果传递给json输出时
return ['data' => $query->all()];

仅传递属性但未传递相关属性 那是我得到的

"data": [
{
  "username": "admin",
  "email": "track.yard@gmail.com",

},
{
  //also id
  "username": "marshal1",
  "email": "marshal1@gmail.com",
  ..... and others

  //i expected to see a role name since there is a related attribute with user id
},

我需要添加什么才能传递相关属性  因为我希望数据也显示角色项名称

这是我的用户模型

    public $role;

public function rules()
{
    return [
        [['username', 'email'], 'filter', 'filter' => 'trim'],
        [['username','expires_on', 'email', 'status'], 'required'],
        ['email', 'email'],
       // ['expires_on', 'integer'],
        [['username','first_name','last_name','firebase_pwd','picture'], 'string', 'min' => 2, 'max' => 255],

        // password field is required on 'create' scenario
        ['password', 'required', 'on' => 'create'],
        // use passwordStrengthRule() method to determine password strength
        $this->passwordStrengthRule(),

        ['username', 'unique', 'message' => 'This username has already been taken.'],
        ['email', 'unique', 'message' => 'This email address has already been taken.'],
    ];
}

   public function fields()
{
    $fields = parent::fields();

    // remove fields that contain sensitive information
    unset($fields['auth_key'], $fields['password_hash'],
        $fields['password_reset_token'],
        $fields['created_at'],
        $fields['firebase_pwd'],
        $fields['updated_at'],
        $fields['id'],
        $fields['authtoken'],
        $fields['account_activation_token']
    );

    $fields['role'] =function ($model){ //added this to see if it'll work
        return $model->role->name;
    };


   return $fields;
}

关系仍在用户模型中

    public function getRole()
{
    // User has_one Role via Role.user_id -> id
    return $this->hasOne(Role::className(), ['user_id' => 'id']);
}

enter code here

4 个答案:

答案 0 :(得分:2)

在联接上使用eager loading并使用asArray()将数据作为数组返回:

$query = User::find()->with('role')->asArray();

$query = User::find()->joinWith('role', true)->asArray();

答案 1 :(得分:0)

您可以设置响应i JSON格式

 \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
 $items = $query->all();
 return ['data' => $items];

或用php编码

$my_json = json_encode($items);

echo $my_json;

答案 2 :(得分:0)

您需要做的就是使用 asArray()

示例:

SAFE_DIVIDE(x, y)

答案 3 :(得分:0)

您可以接收结果到数组并返回相同的@topher。 或者你可以结束阵营。

ArrayHelper::toArray(User::find()->with('role')->all(), [ //or your namespace model 'common\models\User' => ArrayHelper::merge( User::attributes(), ['role' => function($model) { return $model->role; }] ) ])

使用此方法,您可以设置返回结果。

ArrayHelper::toArray(User::find()->all(), [ //or your namespace model 'common\models\User' => [ 'id', 'username' ], ])

Converting Objects to Arrays

P.S这是因为响应准备休息serializer并且它只使用模型中的一个层。