简体   繁体   中英

Yii2 overidden fields()

I have overridden the fields function like so in models/CallerIdentity.php.

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

 return $fields;
} 

CallerIdentity has this relation...

public function getEhadata()
{
  return $this->hasMany(EHAData::className(), ['cidref' => 'cidref']);
}

Controller class is NumbersController. So now if I fire off GET request to api.dev/v1/numbers the response is like so, which is what I was aiming for.

 {
    "cidref": 411,
    "custref": 178,
    "caller_id": "978378478",
    "expiry": "2021-06-27",
    "conf_call": "n",
    "type": "F",
    "redirect": null,
    "destination": "help@help.com",
    "status": 1,
    "start_date": "2010-09-17",
    "last_polled": "2012-12-07 08:30:02",
    "ehadata": [
        {
            "status": 0,
            "name": "Blah ",
            "bussuffix": "Ltd",
            "premesis": "Blah House",
            "thoroughfare": "Blah Road",
            "locality": "Manchester",
            "postcode": "T56 T4G"
        }
    ]
},

Come to writing tests for the endpoint and I cannot access any of the ehadata fields.

I can do:

$I->seeResponseJsonMatchesJsonPath('$[0].ehadata');

va_dump($fields) output

array (size=12)
'cidref' => string 'cidref' (length=6)
'custref' => string 'custref' (length=7)
'caller_id' => string 'caller_id' (length=9)
'expiry' => string 'expiry' (length=6)
'conf_call' => string 'conf_call' (length=9)
'type' => string 'type' (length=4)
'redirect' => string 'redirect' (length=8)
'destination' => string 'destination' (length=11)
'status' => string 'status' (length=6)
'start_date' => string 'start_date' (length=10)
'last_polled' => string 'last_polled' (length=11)
1 => string 'ehadata' (length=7)

To check that the array is there but I can't check any of the individual fields, no matter what I try. This made me think about when I come to write the update function, how can I access/manipulate the fields? Has anyone got any ideas?

Any help would be massively appreciated.

In general, if you override fields() as:

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

 return $fields;
} 

Then accessing the fields will be easy, through looping through $model->ehadata for example, since $model->ehadata is an array of objects

example:

foreach($model->ehadata as $temp)
{
   $temp->status = 2;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM