E
E
Evgeny Bukharev2016-05-18 23:09:03
MySQL
Evgeny Bukharev, 2016-05-18 23:09:03

How to set a composite field in a Yii2 relationship?

Good afternoon,
There was a need to get the hasMany relationship using a composite field:

/**
     * Функция получения рейтинга компании
     * @return integer
     */
    public function getRating()
    {
        return $this->hasMany(Reviews::className(), ['chan_channel' => 'id'])->average('star');
    }

The fact is that in the Reviews table, you need to select records with company_id_{$company_id} in the chan_channel field and calculate AVG ('star') from these records.
That is, records with company_id_1 belong to the company with id=1.
How to specify the company_id_{$company_id} composite field in the hasMany method?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Bukharev, 2016-05-18
@evgenybuckharev

/**
     * Функция генерации строки идентификатора компании в таблице Review
     * @return boolean
     */
    public function getReview_id()
    {
        return 'company_id_'.$this->id;
    }

    /**
     * Функция получения рейтинга компании
     * @return integer
     */
    public function getRating()
    {
        return $this->hasMany(Reviews::className(), ['chan_channel' => 'review_id'])->average('star');
    }

In general, if anyone needs

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question