N
N
nv_vasilencov2020-02-08 14:05:49
Yii
nv_vasilencov, 2020-02-08 14:05:49

How to get nested Yii2 data?

There is a structure
5e3e9337aa0d4467295450.png

How to get the data from the post immediately with the record user and c its position?
Here's what happened so far

public function getUser()
    {
        return  $this->hasOne(User::className(), ['id' => 'userId']);

    }


"data": [
        {
            "id": 161,
            "userId": 2,
            "text": 'Test'
            "user": {
                id:2,
                name: 'Ivan',
                positionId: 7
            }
        }
        ]

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2020-02-08
@nv_vasilencov

The answer is not the one you need, but there is reason to think. If you know how to work with Query Builder from Yii, and also know how to use Join, and understand SQL queries, then use at least bare SQL queries or using QB from Yii. Why? Because the data comes out to you in the form of associative arrays, and you either already drive such an array into your DTO, or work like with a regular array, or reformat this array into json. If you get data by links, then you will have a big performance problem and the code will become bad from this. This is more about when you need data to display a list (index). If you need data in (view), then you can try working on links or widgets there.

M
MSAFT, 2020-02-08
@MSAFT

You have a relationship with User in the Post model. Does User have a connection with Position?
Add to the User model, something like:

public function getPosition()
    {
        return  $this->hasOne(Position::className(), ['id' => 'positionId']);

    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question