Brainfeeder Brainfeeder - 1 year ago 318
reST (reStructuredText) Question

Yii2 REST ActiveRecord deep relation not working

We've been coding an API service with Yii2 and created all model classes extending from ActiveRecord.

Next we started adding the simple relations. This is where things got strange.

We have 3 tables (limited to explain the problem) 'app_customers', 'lu_postcodes' and 'lu_countries'.

A customer has one postcode_id.
A postcode has one country_id.

In the customer model we would like to add relationships to get the postcode and country data when getting customer data.

Customer model:

namespace api\modules\v1\models;

use Yii;
use \api\common\components\BaseModel;

class Customer extends BaseModel {

public function extraFields() {
return ['postcode'];

public function getPostcode() {
return $this->hasOne(Postcode::className(), ['id' => 'postcode_id'])
....[more code]

Postcode model:

namespace api\modules\v1\models;

use Yii;
use \api\common\components\BaseModel;

class Postcode extends BaseModel {

public function extraFields() {
return ['country'];

public function getCountry() {
return $this->hasOne(Country::className(), ['id' => 'country_id']);
....[more code]

So when calling
it returns all customer data and postcode is populated with a postcode object. But we can't get the country data to load together with the postcode data.

In an ideal situation we would like the
actions from customer to include both postcode and country data. (did not try yet .. one step at a time :) )

Trying to debug this issue We dumped the sql from

and got the output:

'SELECT * FROM `lu_postcodes` WHERE `id`=:qp0'

This might have something to do with missing tablenames?

In earlier attempt I managed to get the country data loaded, but it used the ID from customer which resulted in a wrong country obviously.

Any ideas? Thanks in advance!

I did some research and found, which looked promising, but once implemented it still remained the same result.

----------------------- EDIT BELOW

I tried all options and in most cases I get a JSON parse error from Yii. In one case I get a result like

"display_name": "Rxxxxxxx xxxxxxx",
"postcode": {
"id": 361,
"country_id": 20,
"state_id": 2,
"zip": "3945",
"city": "Ham",
"alpha": "ham",
"longitude": "5.1730329000",
"latitude": "51.0966039000"
"country": null

Used option: Adding country in

public function extraFields() {
return ['postcode', 'country' => function($model) { return $model->postcode->country; }];

Answer Source

I got it working. It was an encoding issue...

'charset' => 'UTF-8', in the db config array did the trick.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download