I
I
Isherath2018-09-02 16:27:34
Yii
Isherath, 2018-09-02 16:27:34

Adding arrays to the server response. REST on Yii2?

There is a page with vacancies, which displays vacancies by employer. We need to return a bunch of jobs and information about the employer from the server to display the name of the company so that people can see who owns these jobs. How to do it?
There is an ActiveDataProvider:

$vacancies = new ArrayDataProvider([
            'allModels' => Vacancy::find()->where(['creator' => $creator]),
            'pagination' => [
                'pageSize' => 30
            ]
       ]);
return $vacancies;

All this works well. There is pagination and all that.
But this is only a bunch of vacancies. There is also a request for information about the employer, which returns the name of the company:
$employer = Profile::find()->select('company')->where(['user' => $creator])->one();

How can I combine all this and send it to the client so that I have a pack of vacancies with pagination and info about the employer??

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2018-09-02
@slo_nik

Good evening.
You need to set up links between models.
It looks something like this:
In the profile table, the id of the record is taken, in this case "id" and is looked up in the job table, which should contain "id_company" corresponding to the id of the company profile.

public function getVacancy()
{
    return $this->hasMany(Vacancy::class, ['id_company' => 'id']); // у одного профиля может быть много вакансий
}

public function getProfile()
{
    return $this->hasOne(Profile::class, ['id' => 'id_company']); // у одной вакансии может быть только один профиль.
}

Then your request becomes this:
$vacancies = new ArrayDataProvider([
            'allModels' => Vacancy::find()->with('profile')->where(['creator' => $creator]),
            'pagination' => [
                'pageSize' => 30
            ]
       ]);
return $vacancies;

You can get the profile name like this
More details here .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question