Answer the question
In order to leave comments, you need to log in
How to save a many-to-one set in Yii2?
Hello. So:
1. There is a table Goods
2. There is a table Tech. characteristics
Here is the model of those. characteristics:
class ProductTechSpec extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'product_tech_spec';
}
public function attributeLabels()
{
return [
'id' => 'primary key',
'product_id' => 'primary key',
'title' => 'заголовок',
'spec' => 'описание',
];
}
public function getProduct()
{
return $this->hasOne(Product::className(), ['id' => 'product_id']);
}
public static function find()
{
return new ProductTechSpecQuery(get_called_class());
}
}
public function actionCreate()
{
$model = ['product' => new Product(), 'product_tech_spec' => [new ProductTechSpec()]];
$count = count(Yii::$app->request->post('Setting', []));
for($i = 1; $i < $count; $i++) {
$model['product_tech_spec'][] = new ProductTechSpec();
}
if ($model['product']->load(Yii::$app->request->post()) && $model['product']->save()) {
if (Model::loadMultiple($model['product_tech_spec'], Yii::$app->request->post())){
Model::validateMultiple($model['product_tech_spec'],true);
foreach ($model['product_tech_spec'] as $tech_spec) {
$tech_spec->product_id = $model['product']->id;
$tech_spec->save(false);
}
return $this->redirect(['view', 'id' => $model['product']->id]);
}else{
return $this->render('create', [
'model' => $model,
]);
}
}else{
return $this->render('create', [
'model' => $model,
]);
}
}
Answer the question
In order to leave comments, you need to log in
I don’t quite understand why you put an array with the product and its associated models into the $model variable, they don’t teach this in lessons like this, I also recommend using transactions so that nothing is saved in case of errors somewhere, and of course, you in vain disable validation while maintaining the characteristics.
1) Do
$model['product_tech_spec'] = [new ProductTechSpec()];
for($i = 1; $i < $count; $i++) {
$model['product_tech_spec'][] = new ProductTechSpec();
}
for($i = 1; $i < $count; $i++) {
$model['product_tech_spec'][] = new ProductTechSpec();
}
return $this->render('create', [
'model' => $model,
]);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question