我有两个表格:工作站和路由。该工作站表具有列(station_id,address,office_hours,date_create),Routes表包含列(routes_id,from_id,destination_id)。路由表上的from_id和destination_id是引用站点表的外键。Yii 2:使用保存的数据表的值将数据保存到一个表后填充另一个表
现在我想要做的是无论何时添加一个电台,电台的路线都是使用已经在电台中的电台计算出来的。例如,假设我们已经在车站表中有车站A.将站点B的结果添加到两个路由中,A→B和B→A,从而路由A→B,A =>而B =>目的地,因此他们的ID仅在路由表中被挑选和填充因此。
我已经在车站控制器中尝试了以下代码,但是我没有收到任何成功。该代码是:
StationsController:
public function actionCreate()
{
$model = new Stations();
$routesModel = new Routes();
//checking whether we are getting the logged in user id value
Yii::info("User id=".Yii::$app->user->id);
$model->registered_by_id = Yii::$app->user->id;
$model->status = 10;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//checking here the saved user id value in table
Yii::info("checking User id after saving model=".$model->registered_by_id);
$this->createRoutes($model->station_id);
return $this->redirect(['view', 'id' => $model->station_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function createRoutes($id)
{
$model = new Routes;
$command = Yii::$app->db->createCommand('SELECT station_id FROM stations WHERE station_id !='.$id);
$all_stations = $command->queryAll();
foreach ($all_stations as $new_route) {
$from_id = $id;
$destination_id = $new_route;
$model->load(Yii::$app->request->post()) && $model->save();
$from_id = $new_route;
$destination_id = $id;
$model->load(Yii::$app->request->post()) && $model->save();
}
return;
}
该站表被填充,但是没有填充路由表。但是,我没有收到任何错误。我哪里可能会出错?
请尽可能地协助您。
修订功能createRoutes()
public function createRoutes($id)
{
$model = new Routes;
$count = (new \yii\db\Query())->from('stations')->count();
if($count > 1) {
$command = Yii::$app->db->createCommand('SELECT station_id FROM stations WHERE station_id !='.$id);
$all_stations = $command->queryAll();
foreach ($all_stations as $new_route) {
$model->from_id = $id;
$model->destination_id = $new_route['station_id'];
$model->save();
$model->from_id = $new_route['station_id'];
$model->destination_id = $id;
$model->save();
}
return;
}
else
return;
}
现在,让上述更改后,只保存到数据库的单一路线,但有几个站,因此几条路应创建。如果我有10个电台,它只会为9到10电台生成路由;我的假设是它只保存了foreach外观的最后一部分,在其他情况下,不会调用$ model-> save()参数。我在这里做错了什么?
感谢您的解决方案@leninhasda,我修改了建议的代码,它像魅力一样工作。事实上,我已经注意到,与以前不同,插入值的时间更短。 **虽然有一个更正** 在'createRoutes()'函数的最后一部分中,您有一个使用'Rooutes ::'而不是'Routes ::'的错字。我试图编辑,但它重新发布我早些时候发布的答案。 否则,非常感谢。 – japheth
你能回答我以前问过的其他问题吗? [链接](https://stackoverflow.com/questions/44164746/yii2-admin-rbac-get-roles-from-database-and-display-as-dropdownlist-on-signup-u) – japheth
啊......很好赶上@ japheth和感谢错字报告,现在修复它。我会考虑你的链接,如果我能,我一定会尝试回答它。 – leninhasda