Problem with Single Table Inheritance and fields() method


(Matteolottaroli) #1

Hi guys, I’m developing my application architecture following this link https://github.com/samdark/yii2-cookbook/blob/master/book/ar-single-table-inheritance.md. So I have something like:


backend

|-models

|--Car.php

|--SportCar.php

|--HeavyCar.php

api

|-modules

|--v1

|---models

|----ApiCar.php (extends SportCar)

|---controllers

|----CarController.php (with public $modelClass = 'api\modules\v1\models\ApiCar'<img src='http://www.yiiframework.com/forum/public/style_emoticons/default/wink.gif' class='bbc_emoticon' alt=';)' />



I want to keep separated the api model fields form the backend model fields. Single Table Inheritance is working very well in the backend. Rest web service is up and running.

In the ApiCar class I added the fields() method as described at http://www.yiiframework.com/doc-2.0/guide-rest-resources.html to return a default subset of fields. Something like this:


public function fields() {

	return [

		'title' => function ($model) {

			return $model->name;

		},

		'description' => function ($model) {

			return $model->body;

		},

	];

}



The problem is that the fields() method is literally ignored (I debugged it with breakpoints in phpstorm) and every fields are returned. I tried moving the fields() method in the SportCar class and it is called correctly. Only title and description are returned.

The code in ApiCar model is very trivial


namespace api\modules\v1\models;


class ApiCar extends \backend\models\SportCar

{

    public function fields() {

		return [

			'title' => function ($model) {

				return $model->name;

			},

			'description' => function ($model) {

				return $model->body;

			},

		];

    }

}



And so is the controller


namespace api\modules\v1\controllers;


use api\controllers\ApiController;


class CarController extends ApiController

{

    public $modelClass = 'api\modules\v1\models\ApiCar';

    

    public function actions()

    {

        $actions = parent::actions();

        unset($actions['delete'], $actions['create']);

        

        return $actions;

    }

}

Can someone figure out what am I missing?