Yii2 - 在创建新对象时在一秒 table 内保存固定数据
Yii2 - Saving fixed data in a second table, when create new object
我有两个 tables“项目”和“任务”。它们是相互关联的。
在创建新项目时,我想在保存模型时创建并保存三个相关任务(带有一些固定的预归档信息)。
在 table "tasks" 中,我只想保存与创建的项目和 "task_description" 的关系,这是预定义的。
我在这里迷路了,希望有人能帮助我。如果您需要其他东西,请告诉我。
控制器
Projectscontroller.php
public function actionCreate()
{
$model = new Projects();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} elseif (Yii::$app->request->isAjax) {
return $this->renderAjax('_form', [
'model' => $model
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
模型 Projects.php
public function getTasks()
{
return $this->hasMany(Tasks::className(), ['parent_id' => 'id']);
}
您可以在项目的 afterSave 方法中创建任务:
public function afterSave($insert, $changedAttributes)
{
if ($insert) {
// create your tasks
}
return parent::afterSave($insert, $changedAttributes);
}
您可以使用类似下面的内容
public function actionCreate()
{
$model = new Projects();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$taskmodel=new YourTaskModel();
$taskmodel->project_id=$model->id; // will get inserted project id
$taskmodel->task_description='whateverdescription';
$taskmodel->save();
return $this->redirect(['index']);
} elseif (Yii::$app->request->isAjax) {
return $this->renderAjax('_form', [
'model' => $model
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
基本上您是在将项目保存到数据库中后保存任务。
我有两个 tables“项目”和“任务”。它们是相互关联的。 在创建新项目时,我想在保存模型时创建并保存三个相关任务(带有一些固定的预归档信息)。
在 table "tasks" 中,我只想保存与创建的项目和 "task_description" 的关系,这是预定义的。
我在这里迷路了,希望有人能帮助我。如果您需要其他东西,请告诉我。
控制器 Projectscontroller.php
public function actionCreate()
{
$model = new Projects();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} elseif (Yii::$app->request->isAjax) {
return $this->renderAjax('_form', [
'model' => $model
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
模型 Projects.php
public function getTasks()
{
return $this->hasMany(Tasks::className(), ['parent_id' => 'id']);
}
您可以在项目的 afterSave 方法中创建任务:
public function afterSave($insert, $changedAttributes)
{
if ($insert) {
// create your tasks
}
return parent::afterSave($insert, $changedAttributes);
}
您可以使用类似下面的内容
public function actionCreate()
{
$model = new Projects();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$taskmodel=new YourTaskModel();
$taskmodel->project_id=$model->id; // will get inserted project id
$taskmodel->task_description='whateverdescription';
$taskmodel->save();
return $this->redirect(['index']);
} elseif (Yii::$app->request->isAjax) {
return $this->renderAjax('_form', [
'model' => $model
]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
基本上您是在将项目保存到数据库中后保存任务。