【发布时间】:2017-05-25 17:16:45
【问题描述】:
我有两张表:Stations 和 Routes。 station 表有列(station_id、address、office_hours、date_create),Routes 表有列(routes_id、from_id、destination_id)。 Routes 表中的 from_id 和 destination_id 是引用站表的外键。
现在我想做的是每当添加一个车站时,该车站的路线是使用表中已有的车站计算的。例如,假设我们在站表中已经有站 A。将 B 站结果添加到两条路线 A-->B 和 B-->A 其中对于路线 A-->B,A =>from 而 B => 目的地,因此它们的 ID 仅在路线表中被挑选和填充相应地。
我在工作站控制器中尝试了以下代码,但没有成功。代码是:
站控制器:
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() 参数。我在这里做错了吗?
【问题讨论】: