我有兩個表格:工作站和路由。該工作站表具有列(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