A
A
Artem2015-01-17 02:03:14
Yii
Artem, 2015-01-17 02:03:14

How to properly save related models in yii2?

There is a User model that is associated with another Order model
In User I write the following:

public function getOrders()
    {
     return $this->hasMany(Order::className(), ['id' => 'order_id'])->viaTable('user_order', ['user_id' => 'id']);
    }

How to save relationships to the user_order table while saving user having an array of order models?
The requirements are as follows:
- if there is such a link in the user_order table, then do not touch it
- if it is not enough, then add it
- if the link is not specified when saving, but it exists in the user_order table, then it must be deleted . The
requirements are probably obvious.
I couldn’t find the right method, maybe somehow I didn’t search correctly, I ask for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Kudinov, 2015-01-22
@Frostealth

Unfortunately, yii2 doesn't have link synchronization yet.

$orderKeys = [];
$relatedKeys = [];

foreach ($orders as $model) {
    $orderKeys[] = $model->getPrimaryKey();
}

// получаем айдишники уже связанных заказов
foreach ($user->getOrders()->all() as $model) {
    $relatedKeys[] = $model->getPrimaryKey();
}

// удаляем отсутствующие в $orderKeys связи
foreach (array_diff($relatedKeys, $orderKeys) as $id) {
    $model = Order::findOne($id);
    $user->unlink('orders', $model);
}

// добавляем новые связи
foreach (array_diff($orderKeys, $relatedKeys) as $id) {
    $model = Order::findOne($id);
    $user->link('orders', $model);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question