2016-04-17 4 views
1

Я пытаюсь сохранить многоязычный контент в модели. У меня есть две моделиКак сохранить контент?

PostLang

class PostLang extends \yii\db\ActiveRecord 
     { 

public static function tableName() 
{ 
    return 'postlang'; 
} 

public function rules() 
{ 
    return [ 
     [['post_id', 'lang_id', 'title', 'content'], 'safe'], 
     [['post_id', 'lang_id'], 'integer'], 
     [['title', 'content'], 'string'], 
     [['post_id'], 'exist', 'skipOnError' => true, 'targetClass' => Post::className(), 'targetAttribute' => ['post_id' => 'id']], 
    ]; 
} 
... 
    public function getPost() 
{ 
    return $this->hasOne(Post::className(), ['id' => 'post_id']); 
} 
    } 

и почтовые

class Post extends \yii\db\ActiveRecord { 
     public static function tableName() { 
    return 'post'; 
} 

public function behaviors() { 
    return [ 
     'timestamp' => [ 
      'class' => 'yii\behaviors\TimestampBehavior', 
      'attributes' => [ 
       \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['date_create', 'date_update'], 
       \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['date_update'], 
      ], 
     ], 
    ]; 
} 


public function rules() { 
    return [ 
     [['status', 'date_update', 'date_create'], 'integer'], 
     [['date_update', 'date_create'], 'safe'], 
    ]; 
} 
    ... 
public function getPostlangs() { 
    return $this->hasMany(Postlang::className(), ['post_id' => 'id']); 
} 

}

я создал PostController с создать метод

public function actionCreate() { 
    $model = new Post(); 
    $post_ru = new PostLang(); 
    $post_en = new PostLang(); 

    if ($model->load(Yii::$app->request->post())) { 
     if ($model->save()) { 

      $dbPost = new PostLang(); 
      $dbPost->title = need to save title; 
      $dbPost->content = need to save content; 
      $dbPost->lang_id = need to save lang_id; 
      $dbPost->post_id = $model->id; 
      $dbPost->save(); 
     } 
     return $this->redirect(['view', 'id' => $model->id]); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
     ]); 
    } 
} 

Мне нужно, чтобы сохранить его в foreac h, но я не понимаю, как это сделать. Форма

... 
<?= $form->field($post_ru, 'title')->textInput() ?> 

<?= $form->field($post_ru, 'content')->textInput() ?> 

<?= $form->field($post_en, 'title')->textInput() ?> 

<?= $form->field($post_en, 'content')->textInput() ?> 

...

ответ

1

Вы должны отделить модели в вашем ActiveForm, потому что только последняя модель сохранит.

Форма:

<?= $form->field($post_ru, "[0]title")->textInput() ?> 

<?= $form->field($post_ru, "[0]content")->textInput() ?> 

<?= $form->field($post_en, "[1]title")->textInput() ?> 

<?= $form->field($post_en, "[1]content")->textInput() ?> 

Контроллер:

public function actionCreate() 
{ 
    $model = new Post(); 
    $post_ru = new PostLang(); 
    $post_en = new PostLang(); 
    $postData = Yii::$app->request->post('PostLang'); 
    if ($model->load(Yii::$app->request->post())) { 
     if ($model->save()) { 
      $post_ru->load($postData[0]); 
      $post_en->load($postData[1]); 
      if ($post_ru->save()) { 
       $post_ru->link('post', $model); 
      } 
      if ($post_en->save()) { 
       $post_en->link('post', $model); 
      } 
     } 
     return $this->redirect(['view', 'id' => $model->id]); 
    } else { 
     return $this->render('create', [ 
      'model' => $model, 
     ]); 
    } 
} 

Не забудьте + повторение, если бы это было полезно.

+0

получение ошибки на 'if ($ post_ru-> save()) {' "Нарушение ограничения целостности: 1452 Невозможно добавить или обновить дочернюю строку: ограничение внешнего ключа не выполняется (' asur'.'postlang', CONSTRAINT ' lang-to-post' FOREIGN KEY ('post_id') ССЫЛКИ' post' ('id') ON DELETE CASCADE ON UPDATE CASCADE)" – Slip

+0

Перейдите на панель инструментов отладки yii2 и выберите вкладку db. Будет запрос sql, который не сработает. Отправляйте меня, я проверю. –

Смежные вопросы