在yii迁移中获取select查询的数据
我正在使用yii迁移创建一个父子表,其中子表上有一个外键。我尝试使用execute,但这无助于获取所需的数据。有没有办法查询父表并将父id作为外键插入子表?类似于fetch()/fetchAll()的东西,在phinx迁移中使用在yii迁移中获取select查询的数据,yii,yii2,yii-migrations,Yii,Yii2,Yii Migrations,我正在使用yii迁移创建一个父子表,其中子表上有一个外键。我尝试使用execute,但这无助于获取所需的数据。有没有办法查询父表并将父id作为外键插入子表?类似于fetch()/fetchAll()的东西,在phinx迁移中使用 $this->batchInsert('{{%parent_table}}', ['name'], [ ['P1'],
$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>'],
.
.
.
]
);
$this->batchInsert({{%parent_table}}}),
['name'],
[
['P1'],
['P2'],
['P3'],
['P4']
]
);
$a=$this->execute(“从父表中选择*,其中name='P1'”);
//从表中获取数据,该表将从上述查询中获取id。
$this->batchInsert({{%child_table}}}),
[['name'],['parent_id'],
[
['C1',''],
[C2',''],
.
.
.
]
);
您需要使用
$res = Yii::$app->db->createCommand("select * from parent_table where name = 'P1'")->queryAll();
$this->execute()
用于执行诸如update或delete之类的sql语句
编辑
最好使用
$this->db
而不是Yii::$app->db
来确保您在同一个数据库上运行,正如在评论中提到的那样,最好使用$this->db
组件而不是Yii::$app->db
来确保您在同一个数据库上运行查询。@MichalHynčica。同意。有什么原因不想使用ActiveRecord模型在父表中创建记录吗?您可以在for/foreach循环中创建父记录,然后使用类似于$model->id
的方法获取用于批量插入子记录的父id。@MichalHynčica:我想创建一个迁移脚本,以便将来如果我们要迁移整个数据库,这些值将直接插入到一次迁移中,而不是创建一个脚本使用foreach。由于记录是静态的,所以无论如何,它只是一个一次性脚本。