T
T
tincap2019-02-02 23:49:28
Yii
tincap, 2019-02-02 23:49:28

How to correctly set a selection through a linked table in Yii2?

Let's say we have three tables:

  • user - users
  • currency - selected currency of each user
  • user_currency - link table

user_currency binds the user and currency tables with a foreign key
How do I set a currency selection for the User model in Yii2?
public function getCurrency() {
 ...
}

Is it just like that?
public function getCurrency() {
        $userCurrencyModel = UserCurrency::find()->where(['user_id' => $this->id])->one();
        return $userCurrencyModel->currency;
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valentine, 2019-02-03
@tincap

public function getCurrency() {
    return $this->hasMany(Currency::className(), ['id' => 'currency_id'])
      ->viaTable('user_currency', ['user_id' => 'id']);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question