Answer the question
In order to leave comments, you need to log in
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']);
}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question