在yii迁移中为选择查询提取数据

bwitn5fc  于 2022-11-09  发布在  其他
关注(0)|答案(1)|浏览(97)

我正在使用yii migration创建一个父子表,其中有一个外键在子表上。我尝试使用execute,但它不能帮助我获取所需的数据。有没有方法可以查询父表,并将父ID作为外键插入到子表中?类似于fetch()/fetchAll(),这是在phinx migration中使用的。

$this->batchInsert('{{%parent_table}}',
                ['name'],
                [
                    ['P1'],
                    ['P2'],
                    ['P3'],
                    ['P4']
                ]
            );
    $a = $this->execute("select * from parent_table where name = 'P1'");
    // get the data from the table that will get me the id from the above query.

    $this->batchInsert('{{%child_table}}',
                [['name'],['parent_id']],
                [
                    ['C1','<parent id>'],
                    ['C2','<parent id>'],
                    .
                    .
                    .
                ]
            );
sqyvllje

sqyvllje1#

您需要使用

$sql = <<<SQL
select * from parent_table where name = 'P1'
SQL;

$res = Yii::$app->db->createCommand($sql)->queryAll();

$this->execute()用于执行sql语句,如update或delete。

编辑

最好使用$this->db而不是Yii::$app->db,以确保运行在同一个数据库上,如注解中所述

相关问题