Exemplo n.º 1
0
 /**
  * Move current model after another specified model (ie. `$model->moveAfter($another_model);`)
  * Note: you must manually call refresh() on needed models
  * @param \yii\base\Model $another_model Model taht would be before current model
  */
 public function moveAfter($another_model)
 {
     $field = $this->attribute;
     //! @todo Переписать эти два запроса на один, использующий CASE WHEN THEN
     // shift sort_order field for current model and below
     Yii::$app->db->createCommand("UPDATE " . $this->owner->tableName() . " SET {$field} = {$field} + 1 WHERE {$field} >= :model_sort_order", [':model_sort_order' => intval($another_model->getAttribute($field)) + 1])->execute();
     // shift sort_order field for records upper current
     Yii::$app->db->createCommand("UPDATE " . $this->owner->tableName() . " SET {$field} = {$field} - 1 WHERE {$field} <= :model_sort_order_lower AND {$field} >= :model_sort_order_upper", [':model_sort_order_lower' => intval($another_model->getAttribute($field)) + 1, ':model_sort_order_upper' => intval($this->owner->getAttribute($field))])->execute();
     // change sort_order of our record
     $this->owner->setAttribute($field, $another_model->getAttribute($field));
     $this->owner->save(false, [$field]);
 }