A
A
Arnold2016-01-06 21:55:58
Yii
Arnold, 2016-01-06 21:55:58

Yii2 many-to-many saving via link(), how to organize?

I can’t find a normal example or a detailed description in the documentation, but I can’t understand it by parsing the code :) I
see the same example everywhere:
We define relationships in models

public function getMarkets() {
    return $this->hasMany(Market::className(), ['id' => 'market_id'])
      ->viaTable('tbl_user_market', ['user_id' => 'id']);
}

public function getUsers() {
    return $this->hasMany(User::className(), ['id' => 'user_id'])
      ->viaTable('tbl_user_market', ['market_id' => 'id']);
}

save models:
$user = new User;
$user->name = 'Foo';
$user->save();

$market = new Market;
$market->name = 'Bar';
$market->save();

$user->link('markets', $market);

But I can’t find the CRUD option where I need to save only the User and several Markets selected for it, the documentation is also far from clear, you end up feeling like I’m trying to find a solution by typing.
In general, please tell me how you can save links for many-to-many using link(), otherwise now all this is done in aftoSave in the model and it doesn’t look very nice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Egor, 2016-01-06
@Yii2SlowMoooo

Use this extension

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question