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



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

$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>'],
.
.
.
]
);

您需要使用

$sql = <<<SQL
select * from parent_table where name = 'P1'
SQL;
$res = Yii::$app->db->createCommand($sql)->queryAll();

$this->execute()用于执行sql语句,如更新或删除,而不是

编辑

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

最新更新