M
M
Maxim Fedorov2017-10-04 14:45:04
Yii
Maxim Fedorov, 2017-10-04 14:45:04

Why might there be a bug in the fields of related Yii2 models?

Given: 2 models (Building and Firm), one-to-one relationship (one firm can have 1 building)
In the Firm model, building data is displayed successfully

Model code Company

public function fields()
    {
        return [
            ...
            'building',
        ];
    }

    public function getBuilding()
    {
        return $this->hasOne(Building::className(), ['id' => 'building_id']);
    }

But if I want to display all the companies that it has near the building, then a server error falls
model code Building

public function fields()
    {
        return [
            ...
            'firms',
        ];
    }

    public function getFirms()
    {
        return $this->hasMany(Firm::className(), ['building_id' => 'id']);
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
davidnum95, 2017-10-04
@Maksclub

Try like this:

public function fields()
    {
        return [
            ...
            'firms' => function () {
                return $this->firms;
            },
        ];
    }

V
vkdv, 2017-10-04
@vkdv

Well, logically, you are trying to select many records from another table for one record. I don’t remember exactly how yii2 reacts to this, but in Laravel such a feature will not work (Left join returns as many left records as right ones, this may be a problem with ORM).
You will have to force a call after $Build = Build::findOne(5) (or whatever); $BuildFirms = $Build->firms;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question