single table inheritance

Hi all,

I’ve been using this document to implement single table inheritance with Yii2:

(it is on github samdark/yii2-cookbook/blob/master/book/ar-single-table-inheritance.md, I’m not allowed to insert links)

I followed the code and everything works as expected. Since I have many (~10) classes in the same table, I’d like to limit the amount of copy-and-paste code in the single class file. So I thought about using a trait with the ‘shared’ code.

Using as example the code in the above doc the trait would look like this:




namespace app\models;


trait CarTrait 

{

    

    public function init()

    {

        $this->type = self::TYPE;

        parent::init();

    }


    public static function find()

    {

        return new CarQuery(get_called_class(), ['type' => self::TYPE, 'tableName' => self::tableName()]);

    }


    public function beforeSave($insert)

    {

        $this->type = self::TYPE;

        return parent::beforeSave($insert);

    }

}



and the single class:




namespace app\models;


class SportCar extends Car

{

    const TYPE = 'sport';


    use CarTrait;


}



This doesn’t work. If I do a query like this:




$v = SportCar::find()->all();


foreach( $v as $$car) {

            ....

}



it will generate this error:

yii\base\UnknownPropertyException: Setting unknown property: app\models\CarQuery::type

from the find method in the trait.

If I change the find method like this:




public static function find()

{

    return (new CarQuery(get_called_class()))->where(['type' => self::TYPE]);

}




it works (I get the same result that I get when I use the code from the document above).

My question is: am I missing something? is my code correct? I don’t understand why the original code works and the first version of the trait doesn’t … after all, it is the same code!

Thank you very much

I answer my own question: I resolved using this code by changing CarTrait::find method:




     

    public static function find() {

        return new CarQuery(get_called_class(),['type' => self::TYPE]);

    }



I post here just in case anybody is interested.