Yii 2:使用已保存数据 table 的值将数据保存到一个 Table 后填充另一个 Table

Yii 2: Populate Another Table after Saving Data to One Table using values of the saved data table

我有两个 table:车站和路线。车站 table 有列(station_id、地址、office_hours、date_create),路线 table 有列(routes_id、from_id, destination_id).路由 table 上的 from_id 和 destination_id 是外键引用站 table。

现在我想做的是每当添加一个站点时,该站点的路线都是使用 table 中已有的站点计算的。例如,假设我们已经在站点 table 中有站点 A。将 B 站添加到两条路线,A-->B 和 B-->A,对于路线 A-->B,A =>from 而 B => destination,因此它们的 ID 仅在路线 table相应地。

我在站点控制器中尝试了以下代码,但没有成功。代码是:

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;
}

站点 table 已填充,但路线 table 未填充。但是,我没有收到任何错误。我哪里出错了?

请尽可能提供帮助。

修改函数 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() 参数。我是不是做错了什么?

也许 Yii::$app->request->post() 在函数 createRoules 中不起作用,因为它不是动作函数,但您可以使用 $model->getErrors()查找模型中的错误

我知道这太粗糙了,并且在查询时间方面对系统来说意义重大,但我正在拼命寻找答案。所以到目前为止这对我有用;

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;

    $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) {
            $from_id = $id;
            $destination_id = $new_route['station_id'];
            $sql = 'INSERT INTO routes(from_id, destination_id) VALUES('.$from_id.','.$destination_id.')';
            Yii::$app->db->createCommand($sql)->execute();
            // $model->save();
            $from_id = $new_route['station_id'];
            $destination_id = $id;
            $sql = 'INSERT INTO routes(from_id, destination_id) VALUES('.$from_id.','.$destination_id.')';
            Yii::$app->db->createCommand($sql)->execute();
            // $model->save();
        }
        return;
    }
    else
        return;
}

我仍然欢迎更好的解决方案,尤其是使上述内容如此高效。谢谢大家。

在您的 createRoutes 方法中,您只创建了一个 Routes 模型并填充它并将其保存在循环中,这就是为什么您只获得一条记录的原因。相反,您只需像这样在 foreach 中创建新模型:

public function createRoutes($id)
{
    //$model = new Routes; not here

    // $command = Yii::$app->db->createCommand('SELECT station_id FROM stations WHERE station_id !='.$id);
    // $all_stations = $command->queryAll();

    // I am using  active record instead of single query, you can do anything you want here
    $all_stations = Stations::find()
                ->where('station_id != :id', [':id' => $id])
                ->all();

    foreach ($all_stations as $new_route) {
        $model = new Routes; // create record here
        $model->from_id = $id;
        $model->destination_id = $new_route->station_id;
        // no need to load because these data are not in request param
        // $model->load(Yii::$app->request->post()) && $model->save();
        $model->save();

        $model = new Routes; // and another one
        $model->from_id = $new_route->station_id;
        $model->destination_id = $id;
        $model->save();
    }

    return;
}

重构版本: 以上应该可以解决问题,但这里还有另一个优化。

Routes 模型中创建如下静态方法:

public static function create($data)
{
    $model = new self;
    $model->from_id = $data['from_id'];
    $model->destination_id = $data['destination_id'];
    return $model->save();
}

然后像这样重写 createRoutes 方法:

public function createRoutes($id)
{
    $all_stations = Stations::find()
                ->where('station_id != :id', [':id' => $id])
                ->all();

    foreach ($all_stations as $new_route) {
        Routes::create([
            'from_id' => $id,
            'destination_id' => $new_route->station_id,
        ]);

        Routes::create([
            'from_id' => $new_route->station_id,
            'destination_id' => $id,
        ]);
    }

    return;
}

我们现在有了更干净的版本。