Problems with yii2 associating queries using hasMay

 $order = Orders::find()
        ->where(["order_sn" => $order_sn, "user_id" => Yii::$app->user->identity->id])
        ->all();
        



{
"success": true,
"code": 200,
"message": "OK",
"data": [
    {
        "id": "658",
        "order_sn": "201811088879168432",
        "user_id": "290",
        "order_status": 15,
        "shipping_id": 0,
        "shipping_name": "",
        "pay_id": 0,
        "pay_name": "",
        "goods_amount": "1067.00",
        "user_discount": 100,
        "shipping_fee": "0.00",
        "pay_fee": "0.00",
        "integral_money": "0.00",
        "coupon_id": "0",
        "coupon": "0.00",
        "order_amount": "1067.00",
        "created_at": "1541658432",
        "pay_time": "0",
        "shipping_time": "0",
        "finish_time": "0",
        "shipping_no": "",
        "pay_note": "",
        "ip_address": "127.0.0.1",
        "region_id": 12,
        "coupon_code_id": null,
        "discount_amount": null
    }
]

}

ordes associates multiple tables, but there is only order table data in the json data of the query

previously, if you want to query the associated data in the view, you can use the result set to call it again, for example: $orders- > user- > email;
, but what do you do now in the form of api?

Dec.08,2021

$order = Orders::find()
            ->where(['order_sn' => $order_sn, 'user_id' => Yii::$app->user->identity->id])
            ->all();

$data = [];
foreach ($order as $k => $val) {
      $data[] = [
          'id' => $val->id,
          'order_sn' => $val->order_sn,
          'user_email' => $val->user->email,
           ...
      ];
}

return json_encode($data); 

Model file Orders.php can use fields () method

public function fields()
{
    $fields = parent::fields();
    $extraFields = ['user'];

    return array_merge($fields, $extraFields);
}
Menu