Answer the question
In order to leave comments, you need to log in
Saving and validating relations in yii2 through forms - how to avoid duplicate attributes in a form?
I have a student (id, name, school_id) model and a school (id, name, ...) model.
It turns out that the school has many students
student always belongs to the same school.
class School extends \yii\db\ActiveRecord
{
/*.....*/
public function getStudents()
{
return $this->hasMany(Student::className(), ['school_id' => 'id']);
}
/*.....*/
}
Answer the question
In order to leave comments, you need to log in
If it is relevant for someone, I solved the issue by introducing an additional attribute selectedStudents for the School class, it is not written to the database, it exists purely for the form and for validation rules.
In the afterSave hook in School we do something like this:
$students = Student::find()->where(['id' => $this->selectedStudents])->all();
foreach ($students as $student) {
$student->school_id = $this->id; // еще можно использовать метод link()
$student->save();
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCategories()
{
return $this->hasMany(Category::className(), ['id' => 'category_id'])->viaTable(ProductCategory::tableName(), ['product_id' => 'id']);
}
/**
* @param $value
*/
public function setCategories($value)
{
$this->categories = $value;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question